Reputation: 7160
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);
Upvotes: 9
Views: 35063
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
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
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;
Upvotes: 4
Reputation: 85653
You can use jquery like this:
$(document).append('<div id="wrapper" />');
Upvotes: 1
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