0

need some help over here.

I create and than, store DOM elements in a array.

Later, when i want to use them, they are like unusable, except for the last one.

Here is a realy simple code to illustrate : http://jsfiddle.net/rd2nzk4L/

    var list = new Array();

    // first loop create and store elements
    for (i = 1; i <= 5; i++) {

        var html = '<div id="test-' + i + '" style="float: left; border: 2px solid black; width: 50px; height: 50px; margin: 5px;">' + i + '</div>';

        document.getElementById('test').innerHTML += html;

        var element = document.getElementById('test-' + i);

        //console.log(element);

        list.push(element);

}

// second loop use stored elements
for (index in list) {

    //console.log(list[ index ]);

    list[ index ].style.backgroundColor = 'yellow';

}

You can see only the last element became yellow.

I'll really appreciate if someone have an idea.

Thanks!

  • dont use for...in with arrays as it will iterate over other properties of the array object, unless you do extra checking with hasOwnProperty etc – Patrick Evans Apr 22 '15 at 16:34

3 Answers3

0

Setting the innerHTML of the container will recreate its entire DOM tree.

Therefore, all of the old elements from the previous iteration are no longer attached to the DOM.

You should only set innerHTML once.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

because you aren't creating the elements, so they can't be found with the selector you are using. Try using document.createElement, then div.appendChild(element)

Joe Fitter
  • 1,309
  • 7
  • 11
0

Each time you set the innerHTML of the container, it destroys all of the child elements and recreates them. This is a problem because now your array contains references to elements that no longer exist, apart from the final iteration.

The solution is to work with DOM elements, not raw HTML.

Fiddle

var list = [];

var container = document.getElementById("test");

// first loop create and store elements
for (var i = 1; i <= 5; i++) {

    var element = document.createElement('div');
    element.id = 'test-' + i;
    element.className = 'mydiv';
    element.appendChild(document.createTextNode(i));

    container.appendChild(element);

    list.push(element);
}

// second loop use stored elements
for (var x=0; x<list.length; x++) {
    list[ x ].style.backgroundColor = 'yellow';
}

Side notes:

  • for..in can be used on arrays, but you need to use hasOwnProperty, or just use a basic for loop like above.
  • var list = \[\] is preferred to var list = new Array()more info.
  • Remember to declare count variables like i using var to make them locally scoped, otherwise they will be scoped globally.
Community
  • 1
  • 1
MrCode
  • 63,975
  • 10
  • 90
  • 112