最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Storing DOM reference elements in a Javascript array - Stack Overflow

programmeradmin1浏览0评论

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

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

Anyways, I would like to create a number of DIVISION elements and store the reference into an array so it could be accessed later.

Here's 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 would not work..... There is only 1 div element created. When I use the arr.length to test the code there is only 1 element in the array.

Is there another way to accomplish this?

Thanks in advance

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

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

Anyways, I would like to create a number of DIVISION elements and store the reference into an array so it could be accessed later.

Here's 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 would not work..... There is only 1 div element created. When I use the arr.length to test the code there is only 1 element in the array.

Is there another way to accomplish this?

Thanks in advance

Share Improve this question edited May 24, 2010 at 2:28 Anurag 142k37 gold badges222 silver badges261 bronze badges asked May 23, 2010 at 23:49 Dennis DDennis D 1,3434 gold badges17 silver badges24 bronze badges 1
  • 2 The best way to thank someone is to accept their answer. Someone had to say it :) – alex Commented May 24, 2010 at 0:00
Add a comment  | 

2 Answers 2

Reset to default 16

You are recreating the array with each iteration (and thus blanking it).

I think you want 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);        
};

You're making a separate array each time the loop runs.
Therefore, each array instance

You need to move the arr variable outside the loop.

发布评论

评论列表(0)

  1. 暂无评论