A race is only about 3 or 4 hours long, so it's often possible for them to go before the race, then not have to go again until after. In addition, the inside of the car can get very hot -- 100 degrees Fahrenheit or more -- because of the car's exhaust, which runs just beneath the floor. Because of the heat and the effort they have to expend, they're often more at risk of becoming dehydrated during a race, so they often drink lots of fluids leading up to a race and have a water or energy drink in the car that they'll drink from during caution periods. But, ultimately, if a driver has to go to the bathroom during a race, they would simply relieve themselves in their suit. There's far too much money and prestige at risk to worry about something minor like having to go to the bathroom. Some also wear depends. In most races, the drivers perspire and let out so much body fluid that the wont have to pee. However the occasional pee is required, there is no exact way to do so, but there are many stories of drivers being handed water bottles during pit stops, and even one true story of Tony Stewart defacating in his fire suit. He went on to win, and changed before the interview.
According to NASCAR driver Michael Waltrip, they sweat so much that they seldom have to. He explained that you may lose 5 or 6 pounds in body fluids just from sweating. Race cars are very HOT inside, even the Indy cars. They reach triple-digit temps and then the drivers have on thick firesuits. Therefore, the need to relieve yourself seldom is a problem.