Saving DOM Reference Elements in a Javascript Array

Dear experts, I tried to dynamically generate DOM elements using JS.

I read from Douglas Crockford's book that the DOM is very poorly structured.

In any case, I would like to create several DIVISION elements and store the link in an array so that I can access it later.

Here is the code

for(i=0; i<3; i++) {
    var div = document.body.appendChild(document.createElement("div"));
    var arr = new Array();
    arr.push(div);
}

Somehow this did not work ..... Only one div element is created. When I use arr.lengthto check the code, there is only 1 element in the array.

Is there any other way to do this?

Thanks in advance

+3
source share
2 answers

You recreate the array with each iteration (and thus quenching).

I think you need something like this.

var arr = []; // more succinct version of new Array();

for (var i = 0; i < 3; i++) {
    var div = document.body.appendChild(document.createElement('div'));
    arr.push(div);        
};
+13

, .

arr .

+3

Source: https://habr.com/ru/post/1746803/


All Articles