There are two problems with your loop:
You're looping through a list of elements, there's no need to then go try to get them by
id
. so change these two lines:var object = elements[i].id; document.getElementById(object).className='hidden';
to:
elements[i].className='hidden';
Changing that fixes the problem: Compare this working version (source) to your original (source), but I haven't figured out yet why. :-)
getElementById
is returningnull
even though you've clearly assigned theid
s (and in fact, we're getting them correctly from the elements).But while the above is something you need to fix, it's not why you're having the error. The error is coming from your using
for-in
to loop through theNodeList
. Use a normalfor
loop:for (var i = 0; i < elements.length; ++i) {
Remember that
for-in
is not about looping through array elements (and the return value fromgetElementsByClassName
is not an array), it's about looping through the enumerable property names of an object. In your case, you see it loop twice: Once for the property"0"
, and once for the property"length"
. Since you don't have an element with theid
"length"
, your next line blows up, sincegetElementById
returnsnull
for thatid
.More about the myths and realities of
for-in
on my blog, and more about various "correct" ways to loop through arrays (although again, that's not whatelements
is in your code) here on Stack Overflow.