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
With document. createElement() method you can create a specified HTML element dynamically in JavaScript. After creation you can add attributes. If you want the element to show up in your document, you have to insert in into the DOM-tree of the document.
Block elements are not allowed inside inline elements. In this case, the button and img tags are inline elements while div, h3 and p tags are block elements. So, it's still invalid.
A child is an element that is directly below and connected to an element in the document tree.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With