Create a div element and dynamically add child elements to it

How to create an element in javascript and dynamically add elements to it?

If I have this created element in HTML and dynamically add elements to it, it works fine.

<!-- THIS WILL WORK -->
<div id="wrapper"></div>

But this will not work:

// THIS WILL NOT WORK
var container = document.createElement('div');
container.id = "wrapper";

Additional code:

var html = '<div><ul>';

for(var i=1; i<=40; i++){
    html+= "<li>Testing: "+i+"</li>";
}

html+= '</ul></div>';

$('#wrapper').append(html);

Fiddle

+3
source share
4 answers

Here is your code:

$(function() {
var container = document.createElement('div');
container.id = "wrapper";

$('body').append(container);

var html = '<div><ul>';

for(var i=1; i<=40; i++){
    html+= "<li>Testing: "+i+"</li>";
}

html+= '</ul></div>';

$('#wrapper').append(html);
});
+8
source

You must call appendChild(element)to add items. For instance:

var h1 = document.createElement("h1");
h1.textContent = "Title";
document.body.appendChild(h1);

In your case, this is:

var parent = document.body; // or another one like document.getElementById("othercontainer")
parent.appendChild(container);
+4
source

You can use jquery as follows:

$(document).append('<div id="wrapper" />');
+1
source

You need to insert your wrapper on the HTML page.

This will work:

HTML:

<div id="layout">

</div>

JS:

var container = document.createElement('div');
container.id = "wrapper";

var layout = document.getElementById('layout');
layout.appendChild(container);

var html = '<div><ul>';

for(var i=1; i<=40; i++){
    html+= "<li>Testing: "+i+"</li>";
}

html+= '</ul></div>';

container.innerHTML = html;

http://jsfiddle.net/Zd2rw/

+1
source

All Articles