Marek Bernád
Marek Bernád

Reputation: 639

I cannot append elements with jQuery during javascript loop

There is one similar question, but I still not understand why I can't do the following:

            var numLoaded = document.createElement('span')
            numLoaded = document.createElement('span')
            numLoaded.style= "color:red;font-weight:bold";

            numLoaded.innerHTML = " Number of loaded results: "+0;

            $("#resultsCounter").append(numLoaded)

            for (var i = ((json.length)-1); i >= 0; i--) { 
                newDiv = document.createElement("div");
                newDiv.id = +i+1;
                newDiv.innerHTML = newDiv.innerHTML+"..."

                numLoaded.innerHTML = " Number of loaded results: "+newDiv.id;
                $("#resultsCounter").empty(); // should remove my span
                $("#resultsCounter").append(numLoaded) // should add my span with new content
                $("#results").prepend(newDiv)
            }

After this all as output I see only last added element after whole cycle ends. During cycle iteration it appends to DOM no child, even if it is already created. I want to append always the same element <span> but in every iteration with updated number.

Why child element is added to DOM only after cycle ends? How to update it in cycle? Do I need to recreate that element after every loop iteration? It is way to speed up this process?

Upvotes: 0

Views: 183

Answers (1)

Robin Zigmond
Robin Zigmond

Reputation: 18259

It's because you only create the element once, before the list. Then in the loop you are changing the innerHtml of the element, and adding it - but because it is the same element (the same JS object being referenced each time), it's effectively overwriting itself.

You just need to move these lines which create the element:

var numLoaded = document.createElement('span')
numLoaded = document.createElement('span')
numLoaded.style= "color:red;font-weight:bold";

numLoaded.innerHTML = " Number of loaded results: "+0;

inside the loop.

Upvotes: 1

Related Questions