Create divs dynamically

Go To StackoverFlow.com

1

I want to create as many divs as var foo.length, but my code only creates one div.

var foo = new Array();
for ( i = 0; i < 5; i++ ) { 
  foo[i] = document.createElement('div'); 
}

Can someone help me?

2012-04-04 05:27
by NoName
You should declare variables: for (var i=0; ...). That isn't your issue though, the code looks like it should work - RobG 2012-04-04 05:34
Works fine, but only return one div create; i want to create - NoName 2012-04-04 05:35
Your code produces 5 diffrent HTMLDivElement's no worries there. Also instead of creating the array with new Array();, use the more literal type []. You need to append the divs to the document or another container of sorts - Henrik Andersson 2012-04-04 05:37


5

Calling "document.createElement" doesn't actually add the new element to the DOM, it just creates it. You need to then call 'appendChild'. So something like this:

var container = document.getElementById('container');
var foo = [];
for (var i = 0;i < 5;i++) {
    foo[i] = document.createElement('div');
    container.appendChild(foo[i]);
}
2012-04-04 05:35
by McGarnagle
Don't forget to update code to avoid confusion! : - Henrik Andersson 2012-04-04 05:46
Yes, have to add the
somewhere, of course .. - McGarnagle 2012-04-04 05:48
And var foo = []; ; - Henrik Andersson 2012-04-04 05:54
Ads