Dynamically create a <div> element with JavaScript/jQuery
This post will discuss how to dynamically create a <div> element in JavaScript and jQuery.
1. Using JavaScript
In vanilla JavaScript, you can use the native createElement() method to create an HTML <div> element and the appendChild() method to append the <div> element to another container.
JS
|
1 2 3 4 5 6 7 8 |
document.addEventListener('DOMContentLoaded', function() { var div = document.createElement('div'); div.id = 'container'; div.innerHTML = 'Hi there!'; div.className = 'border pad'; document.body.appendChild(div); }, false); |
HTML
|
1 2 3 4 |
<!doctype html> <html lang="en"> <body></body> </html> |
CSS
|
1 2 3 4 5 6 7 |
.border { border: 1px solid grey; } .pad { padding: 15px; } |
2. Using jQuery
With jQuery, you can use the .append() method to append the <div> element at the end of the specified container.
JS
|
1 2 3 4 5 6 7 8 9 |
$(document).ready(function() { $('#outerdiv').append( $('<div>').prop({ id: 'innerdiv', innerHTML: 'Hi there!', className: 'border pad' }) ); }); |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <div id="outerdiv"></div> </body> </html> |
CSS
|
1 2 3 4 5 6 7 |
.border { border: 1px solid grey; } .pad { padding: 15px; } |
This can be shortened to:
JS
|
1 2 3 |
$(document).ready(function() { $('#outerdiv').append('<div id="innerdiv" class="border pad">Hi there!</div>'); }); |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <div id="outerdiv"></div> </body> </html> |
CSS
|
1 2 3 4 5 6 7 |
.border { border: 1px solid grey; } .pad { padding: 15px; } |
Here’s alternate version using .appendTo() method:
JS
|
1 2 3 |
$(document).ready(function() { $('<div id="innerdiv" class="border pad">Hi there!</div>').appendTo('#outerdiv'); }); |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <div id="outerdiv"></div> </body> </html> |
CSS
|
1 2 3 4 5 6 7 |
.border { border: 1px solid grey; } .pad { padding: 15px; } |
That’s all about dynamically creating a div element in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)