javascript - variable turns to undefined inside a for loop -
i'm battling javascript function i'm working on.
inside loop i'm iterating elements class "visible", inside loop i'm preforming 2 actions.
- elements[i].removeattribute("class");
- elements[i].setattribute("class", "hidden");
for reason 1 valid. 2 produces error saying:
uncaught typeerror: cannot call method 'setattribute' of undefined
even when log elements[i] using console.log; after first console.log call element exists, on second console.log elements[i] 'undefined'
what hell missing here, driving me crazy, if laptop wasn't expensive have been broken now. :(
here's function:
function hide_visable_elements() { // remove body eventlistener var body = document.getelementsbytagname("body"); body[0].removeeventlistener("click", hide_visable_elements, true); var elements = document.getelementsbyclassname("visible"); (var = 0; < elements.length; i++) { console.log(elements[i]); // works swiss clock elements[i].removeattribute("class"); console.log(elements[i]); // why elements[i] 'undefined' ??? elements[i].setattribute("class", "hidden"); // << turns useless code } }
getelementsbyclassname
live nodelist
changing classname
of items affects whole list. recommend use queryselectorall insead.
plus instead of var body = document.getelementsbytagname("body");
use document.body
.
Comments
Post a Comment