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.

  1. elements[i].removeattribute("class");
  2. 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

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -