JavaScript .innerHTML
Published Mar 16, 2025
Contribute to Docs
The .innerHTML property in JavaScript is a fundamental DOM (Document Object Model) manipulation tool that allows setting or retrieving the HTML content inside an element. It allows developers to dynamically modify a webpage’s content by reading or writing HTML markup as a string. When setting .innerHTML, the browser parses the provided string as HTML and updates the DOM accordingly. This property is particularly useful for inserting multiple elements or complex HTML structures at once.
Syntax
// Getting HTML content
const content = element.innerHTML;
// Setting HTML content
element.innerHTML = htmlString;
element: The DOM element whose content is being accessed or modified.htmlString: A string containing HTML markup to be injected.
When reading .innerHTML, it returns the current HTML string inside the element.
Notes
- Setting
.innerHTMLreplaces all existing content within the element. - The provided HTML string is parsed and valid HTML tags are converted to DOM elements.
- Be cautious with user-provided content as
.innerHTMLcan execute scripts, making it vulnerable to XSS (Cross-Site Scripting) attacks. - For plain text content, consider using
.textContentfor better security and performance. - If an element contains event handlers, replacing
.innerHTMLwill remove them. Consider.appendChild()for better control.
Example
Here’s how to use .innerHTML to modify content in a <div>:
// Select the <div> element with the id 'container'const container = document.getElementById('container');// Set new HTML contentcontainer.innerHTML = '<p>This paragraph was added using innerHTML!</p>';// Get the current HTML contentconsole.log(container.innerHTML); // "<p>This paragraph was added using innerHTML!</p>"// Replace with more complex HTMLcontainer.innerHTML = `<h2>Dynamic Content</h2><p>First paragraph</p><ul><li>Item 1</li><li>Item 2</li></ul>`;
The above code produces the following output:
"<p>This paragraph was added using innerHTML!</p>"
After execution, the <div> will contain:
<div id="container"><h2>Dynamic Content</h2><p>First paragraph</p><ul><li>Item 1</li><li>Item 2</li></ul></div>
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
- Includes 34 Courses
- With Professional Certification
- Beginner Friendly.115 hours
- Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
- Beginner Friendly.15 hours