Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elements not added to DOM by generator function

Tags:

javascript

dom

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();
like image 827
JS- Avatar asked Jan 12 '23 04:01

JS-


1 Answers

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();
like image 87
Gurpreet Singh Avatar answered Jan 17 '23 12:01

Gurpreet Singh