HTML DOM Element innerHTML Property

Definition and Usage

innerHTML Sets or returns the HTML content (inner HTML) of an element.

See also:

innerText property

textContent property

Instance

Example 1

Get the HTML content of the element with id="myP":

let html = document.getElementById("myP").innerHTML;

Try it yourself

Example 2

Change the HTML content of the element with id="demo":

document.getElementById("demo").innerHTML = "I have changed!";

Try it yourself

Example 3

Get the HTML content of the <ul> element with id="myList":

let html = document.getElementById("myList").innerHTML;

Try it yourself

Example 4

Remove the HTML content of the <p> element with id="demo":

element.innerHTML = "";

Try it yourself

Example 5

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 6

Repeat the HTML content of the element:

element.innerHTML += element.innerHTML;

Try it yourself

Example 7

Change the HTML content and URL of the link:

element.innerHTML = "W3School";
element.href = "";

Try it yourself

Syntax

Return the innerHTML property:

element.innerHTML

Set the innerHTML property:

element.innerHTML = text

Attribute value

Value Description
String. HTML content.

Return value

Type Description
String The HTML content of the element.

The difference between innerHTML, innerText, and textContent

The innerText property returns:

Only returns the text content of the element and all its child elements, without CSS hidden text spacing and tags, except for <script> and <style> elements.

The innerHTML property returns:

The text content of the element, including all whitespace and internal HTML tags.

The textContent property returns:

The text content of the element and all its descendants, including whitespace and hidden CSS 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 above example:

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

All browsers support element.innerHTML:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support Support Support Support Support Support