Okay, obviously I’m new to javascript. I’m trying to use radio buttons to hide divs by class, my function needs to hide all the divs with either class name “p12” or “p34” when a single radio is clicked.
BUT
This is only working for all the p12 divs…. what am I missing to make both?..
if (document.getElementById('numbofextras0').checked == true) {
for(i=0; i<100; i++)
document.getElementsByClassName('p12')[i].style.display = 'none';
for(i=0; i<100; i++)
document.getElementsByClassName('p34')[i].style.display = 'none';
}
I wouldn’t be surprised if it doesn’t like you possibly going outside the range of what the
getElementsByClassNamereturns (but then again, I haven’t tested/checked what would happen). Try storing the results first, then looping through them.This way, it loops over the exact amount of elements (you don’t have hardcode
100in) that eachgetElementsByClassNamereturns.The main problem is that when you hardcode
100in, it will always loop from 0 to 99. IfgetElementsByClassNamereturns less than 100 elements, trying to access that index will return undefined and throw an exception when you try to do something like.style.display = "none";. Or what if there’s 160 elements returned? Only the first 100 will be modified. Making the call before the loop and storing the returned elements in a variable, then looping through that length, is the safe/correct way. The way you had it before, it was making a call togetElementsByClassNameon every loop iteration – very inefficient – you only need to do it once!…and of course, hardcoding100wasn’t the best way to loop through the elements. It was all the right idea, just not the right order. I mean, technically, you could’ve done something like this:But like I said, calling
getElementsByClassNameon every loop iteration isn’t very efficient.