The innerHTML property of a DOM element allows you to get or set the HTML markup inside that element. Using innerHTML, you can dynamically change the content and structure of a webpage with JavaScript.
It is one of the most commonly used properties when working with the DOM because it lets you insert, replace, or append HTML content as a string.
element.innerHTML.innerHTML completely replaces the existing content.+= with innerHTML lets you add new HTML without removing the old content.<p>, <strong>, <li>, etc.innerHTML changes, the browser rebuilds the DOM inside that element.Basic syntax:
element.innerHTML → returns the HTML markup inside the element as a string.element.innerHTML = "new HTML" → replaces the existing HTML inside the element.Since innerHTML works with strings, the HTML tags inside must be written as a valid HTML string. When working inside JavaScript, you usually need to escape the angle brackets using entities like < and > if you are writing them inside another HTML document.
// Get the current HTML content
const container = document.getElementById("container");
console.log(container.innerHTML);
// Set new HTML content
container.innerHTML = "<p>New <strong>HTML</strong> content</p>";
const list = document.getElementById("myList");
list.innerHTML += "<li>New Item</li>";
HTML:
<div id="container">
<p>Old content</p>
</div>
JavaScript:
const container = document.getElementById("container");
container.innerHTML = "<h2>Updated Content</h2><p>This is new content.</p>";
Below is a simple interactive example. Click the button to update the content of the box using innerHTML.
This text will be replaced using innerHTML.
When you click the button, JavaScript selects the <div> with id="demoBox" and replaces its entire inner HTML with a new heading and paragraph. This demonstrates how innerHTML can change both text and structure at once.
innerHTML when you need to insert or replace HTML markup dynamically.innerHTML replaces all existing content inside the element.innerHTML += ... if you want to append without removing existing content.innerHTML.createElement and appendChild for better performance.innerHTML to change the structure of a webpage dynamically (e.g., replace a paragraph with a list).innerHTML +=.innerHTML affects the DOM tree using your browser's developer tools.innerHTML to an empty string "". What happens to the element's content?innerHTML assignment.innerHTML inside a button click event (similar to the demo above).appendChild) instead of innerHTML.