DEV Community

Steph
Steph

Posted on • Updated on

The Difference Between HTML DOM Properties: innerHTML, innerText, and textContent

When you’re starting out learning JavaScript it can be challenging to understand the differences between innerHTML vs innerText vs textContent. While all three are DOM properties that allow you to set or return the content of HTML elements, they each have different use cases. Let’s start by breaking down the major differences between the three in the chart below.

Key Differences

Image description

Source: W3 Schools definitions

Example

Let’s go through an example that further illustrates the difference between the three properties.

Here's our starting HTML:

<p> Paragraph demonstrating the <span style="color:purple">difference</span> between       innerHTML, innerText, and textContent.</p>
Enter fullscreen mode Exit fullscreen mode

As well as what it looks like rendered in the browser:

Image description

Here's the JavaScript where we're applying innerHTML, innerText, and textContent to our paragraph element:

const paragraphText = document.querySelector("p");

//innerHTML//
function innerHTMLTest() {
    console.log("innerHTML:" + paragraphText.innerHTML);
}
innerHTMLTest();


//innerText//
function innerTextTest() {
    console.log("innerText:" + paragraphText.innerText);
}
innerTextTest();


//textContent//
function textContentTest() {
    console.log("innerContent:" + paragraphText.textContent);

textContentTest();
Enter fullscreen mode Exit fullscreen mode

What appears in the console:

Image description

When to Use Each Property

innerHTML

innerHTML is great to use when you’re looking to see or replace the HTML content inside of an element. It can be especially helpful if you’re looking to quickly and easily replace a large amount of HTML or empty an HTML element (eg. empty a div tag using div.innerHTML = “”).

To continue our example from above, you could use innerHTML to completely swap the text in our paragraph with an unordered list:

const paragraphText = document.querySelector(‘p’);

paragraphText.innerHTML = “
<ul> 
    <li>List item one</li> 
    <li>List item two></li> 
    <li>List item three></li>
</ul>”;
Enter fullscreen mode Exit fullscreen mode

innerText

innerText is used when you want to see or replace the text inside an element or node, but you don’t care about additional formatting like spacing. This is the property that I end up using the most often when I’m trying to replace any text within an HTML element since I’m often not running into a lot of additional styling or spacing within the text.

textContent

textContent is used when you want to see or replace the text inside an element or node, including any styling.

Top comments (0)