Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 510
JunM Avatar asked Feb 11 '14 08:02

JunM


People also ask

How do I create a dynamic element in HTML?

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.

Can Div be child of button?

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.

What are child elements in HTML?

A child is an element that is directly below and connected to an element in the document tree.


1 Answers

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);
});
like image 164
Jokey Avatar answered Sep 19 '22 16:09

Jokey