javascript - Elements not added to DOM by generator function -


i have been pulling hair out trying make simple code work. should render input fields in given dom, doesn't. why not?

var elems = 10;  function generateelems() {      (var = 0; < elems; i++) {         document.getelementsbytagname("div")[0].appendchild(document.createelement('input'));     }      //clean     var obj = null;     var elems = null; }  generateelems(); 

working demo

you dealing javascript variable hoisting here. remove line var elems = null; , code should work.

it considered best practise in javascript declare variables @ top of function body.

read article more information on javascript hoisting.

as discussing best practises, it's worth making note appending elements in loops bad idea performance. should use createdocumentfragment instead append elements , dump dom. saves expensive document reflows , makes significant difference in performance.

var elems = 10;  function generateelems() {      var d=document.createdocumentfragment();      (var = 0; < elems; i++) {         d.appendchild(document.createelement('input'));     }      document.getelementsbytagname('div')[0].appendchild(d);       //clean     //var obj = null;     //var elems = null;  ----> commented out line, causing problem.   }  generateelems(); 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -