JunM
JunM

Reputation: 7160

Create div element and dynamically add child elements on it

How do I create an element in javascript and dynamically add elements on it?

If I have this created element on HTML and dynamically append elements on it, it works just 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

Upvotes: 9

Views: 35063

Answers (5)

Souradeep Nanda
Souradeep Nanda

Reputation: 3298

Here is an unsafe way of doing it. You can just edit the innerHTML as a string.

hd = document.getElementsByTagName('head').item(0)
hd.innerHTML += '<style>body {background-color:blue;}</style>'

Upvotes: 0

Jokey
Jokey

Reputation: 314

Here's 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);
});

Upvotes: 10

C&#233;dric Babeix
C&#233;dric Babeix

Reputation: 139

You need to insert your wrapper in your HTML page.

This would 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/

Upvotes: 4

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85653

You can use jquery like this:

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

Upvotes: 1

dooxe
dooxe

Reputation: 1490

You have to call appendChild(element) to add elements. For example:

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

Upvotes: 8

Related Questions