I have been pulling my hair out trying to make this simple code work. It should render input fields in the given DOM, but it doesn't. Why not?
var elems = 10;
function generateElems() {
for (var i = 0; i < elems; i++) {
document.getElementsByTagName("div")[0].appendChild(document.createElement('input'));
}
//Clean up
var obj = null;
var elems = null;
}
generateElems();
Working DEMO
You are dealing with JavaScript variable hoisting here. Remove this line var elems = null;
and your code should work.
It is considered best practise in JavaScript to declare all variables at the top of the function body.
Read this article for more information on JavaScript hoisting.
As we are discussing best practises, it's worth making a note that appending elements in loops is a bad idea for performance. You should use createDocumentFragment
instead to append the elements to and then dump this to DOM. It saves expensive document reflows and makes significant difference in performance.
var elems = 10;
function generateElems() {
var d=document.createDocumentFragment();
for (var i = 0; i < elems; i++) {
d.appendChild(document.createElement('input'));
}
document.getElementsByTagName('div')[0].appendChild(d);
//Clean up
//var obj = null;
//var elems = null; ----> Commented out this line, it was causing the problem.
}
generateElems();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With