Insert HTML into a div with JavaScript/jQuery
This post will discuss how to insert HTML into a div in JavaScript and jQuery.
1. Using jQuery
With jQuery, you can use the .append() method to insert the specified HTML as the last child of the div container.
JS
|
1 2 3 |
$(document).ready(function() { $('#container').append('<button id="submit">Submit</button>'); }); |
HTML
|
1 2 3 4 |
<div id="container"> <label>Enter your name:</label> <input type="text"> </div> |
To insert the specified content as the first child of the div container, consider using the .prepend() method instead.
JS
|
1 2 3 |
$(document).ready(function() { $('#container').prepend('<label>Enter your name:</label>'); }); |
HTML
|
1 2 3 4 |
<div id="container"> <input type="text"> <button id="submit">Submit</button> </div> |
2. Using JavaScript
In plain JavaScript, the innerHTML property is often used to replace the contents of an element. To insert the HTML into a container rather than replacing its entire contents, you can use the += operator, as shown below:
JS
|
1 |
document.getElementById('container').innerHTML += '<button id="submit">Submit</button>'; |
HTML
|
1 2 3 4 |
<div id="container"> <label>Enter your name:</label> <input type="text"> </div> |
Instead of directly changing the innerHTML, you should use the appendChild() method.
JS
|
1 2 3 |
var button = document.createElement('button'); button.innerHTML = 'Submit'; document.getElementById('container').appendChild(button); |
HTML
|
1 2 3 4 |
<div id="container"> <label>Enter your name:</label> <input type="text"> </div> |
Alternatively, JavaScript has a native method insertAdjacentHTML() to insert the HTML into the document. It takes the position relative to the element, which can be either:
'beforebegin': Before the element itself.'afterbegin': Just inside the element, before its first child.'beforeend': Just inside the element, after its last child.'afterend': After the element itself.
JS
|
1 2 |
var html = '<button id="submit">Submit</button>'; document.getElementById('container').insertAdjacentHTML('afterend', html); |
HTML
|
1 2 3 4 |
<div id="container"> <label>Enter your name:</label> <input type="text"> </div> |
That’s all about inserting HTML into a div 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 :)