user1305760
user1305760

Reputation:

Create divs dynamically

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?

Upvotes: 1

Views: 1339

Answers (1)

McGarnagle
McGarnagle

Reputation: 102723

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]);
}

Upvotes: 5

Related Questions