4

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

1
  • 2
    The best way to thank someone is to accept their answer. Someone had to say it :) Commented May 24, 2010 at 0:00

2 Answers 2

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);        
};
Sign up to request clarification or add additional context in comments.

1 Comment

@webzide, don't forget to click the check button next to alex's post so he gets credit!
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.