Replace content of a div element with JavaScript/jQuery
This post will discuss how to replace the content of a div element in JavaScript and jQuery.
1. Using JavaScript
The most common approach to replace the content inside an element is with the innerHTML property. Alternatively, you can use the textContent to set the element’s text content, which is considered safe against XSS attacks.
JS
|
1 |
document.getElementById('container').innerHTML = 'Hi there!'; |
HTML
|
1 |
<div id="container"></div> |
2. Using jQuery
With jQuery, you can use the .html() to replace the contents of any element which uses the browser’s innerHTML property. You can also use the .text() method.
jQuery
|
1 2 3 |
$(document).ready(function() { $("#container").html('Hi there!'); }); |
HTML
|
1 |
<div id="container"></div> |
3. Using Prototype.js
If you’re using the Prototype.js library, consider using the update() method.
Prototype.js
|
1 |
$('container').update('Hi there!'); |
HTML
|
1 |
<div id="container"></div> |
That’s all about replacing the content of 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 :)