Tóm Tắt
HTML DOM Element innerHTML
Definition and Usage
The innerHTML
property sets or returns the HTML content (inner HTML) of an element.
The Differences Between
innerHTML, innerText and textContent
See below
Syntax
Return the innerHTML property:
element.innerHTML
Set the innerHTML property:
element.innerHTML = text
Property Value
Property
Description
StringHTML content.
Return Value
Type
Description
StringThe HTML content of the element.
More Examples
Example
Change the HTML content of two elements:
let text = “Hello Dolly.”;
document.getElementById(“myP”).innerHTML = text;
document.getElementById(“myDIV”).innerHTML = text;
Try it Yourself »
Example
Repeat the HTML content of an element:
element.innerHTML += element.innerHTML;
Try it Yourself »
Example
Change the HTML content and URL of a link:
element.innerHTML = “W3Schools”;
element.href = “https://www.w3schools.com”;
Try it Yourself »
The Differences Between
innerHTML, innerText and textContent
The innerHTML property returns:
The text content of the element, including all spacing and inner HTML tags.
The innerText property returns:
Just the text content of the element and all its children, without CSS hidden text spacing and tags,
except <script> and <style> elements.
The textContent property returns:
The text content of the element and all descendaces, with spacing and CSS hidden text,
but without tags.
HTML Example
<p id=”myP”> This element has extra spacing and contains <span>a span
element</span>.</p>
JavaScript Examples
let text = document.getElementById(“myP”).innerText;
let text = document.getElementById(“myP”).innerHTML;
let text = document.getElementById(“demo”).textContent;
Try it Yourself »
In the example above:
The innerText property returns:
This element has extra spacing and contains a span element.
The innerHTML property returns:
This element has extra spacing and contains <span>a span element</span>.
The textContent property returns:
This element has extra spacing and contains a span element.
Browser Support
element.innerHTML
is supported in all browsers:
Chrome
IE
Edge
Firefox
Safari
Opera
Yes
Yes
Yes
Yes
Yes
Yes