HTML Element .innerHTML
| Since: | HTML5(2014) |
|---|
Gets or sets the HTML inside an element as a string. Because HTML tags are interpreted as markup, use this property when you need to dynamically insert HTML.
Syntax
var html = element.innerHTML; element.innerHTML = "<p>New text</p>";
Sample Code
<div id="profile"> <p><strong>user_a</strong> — org_a</p> </div> <div id="member-list"></div> <div id="output"></div>
This produces the following output:
var profile = document.getElementById("profile");
console.log(profile.innerHTML); // Outputs "<p><strong>user_a</strong> — org_a</p>"
// Pattern 2: Replace with new HTML (tags are interpreted as markup)
var members = ["item_a", "item_b", "item_c", "item_d"];
var html = "<ul>";
for (var i = 0; i < members.length; i++) {
html += "<li>" + members[i] + "</li>";
}
html += "</ul>";
var list = document.getElementById("member-list");
list.innerHTML = html;
// Pattern 3: Append HTML to the end (using +=)
var output = document.getElementById("output");
output.innerHTML += "<p>count: " + members.length + "</p>";
// Pattern 4: Clear the content
output.innerHTML = "";
Result
Running pattern 2 above changes the HTML as follows.
<!-- Before --> <div id="member-list"></div>
<!-- After setting innerHTML --> <div id="member-list"> <ul><li>item_a</li><li>item_b</li><li>item_c</li><li>item_d</li></ul> </div>
<!-- After innerHTML = "" --> <div id="output"></div>
Unlike element.textContent, HTML tags are interpreted as markup and actual elements are created in the DOM.
Security Note
Inserting user-supplied input directly via element.innerHTML can allow malicious scripts to execute (XSS: Cross-Site Scripting).
var userInput = '<img src=x onerror="alert(document.cookie)">'; element.innerHTML = userInput; // The script will be executed. // Use textContent for user input — it is safe. element.textContent = userInput; // Displayed as a plain string.
Overview
element.innerHTML is a property that gets or sets the content of an element as an HTML string. When getting, it returns the string including any tag structure. When setting, the string is parsed as HTML and reflected in the DOM.
To clear an element's content, simply assign an empty string: element.innerHTML = "".
When displaying user input, it is recommended to use element.textContent for security reasons. Use element.innerHTML only when inserting trusted HTML dynamically.
element.innerHTML is covered in more detail in the tutorial article Changing Element Content with innerHTML. Feel free to check it out.
Browser Compatibility
3 or earlier ×
7 or earlier ×
Android Browser
37+ ○
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.