DOM : innerText || innerHTML || textContent

Tosh
2 min readJul 27, 2020

--

These three properties look similar but let’s dive in and see the differences during our Dom manipulation.

Let’s see the differences between innerHTML, innerText, and textContent by manipulating the DOM with JavaScript .

We start with a HTML sample and take a look how each property works.

<div id='myDiv'>

<span>Hello <span style="display: none;">World</span></span>
</div>const myDiv = document.getElementById('myDiv');

Above we have a div tag with myDiv for ID and contain a span tag. This span as the word “Hello” and an other span tag with the word “World” and a style display non as attribute so this code will render only “Hello” in our web page .

We create a variable myDiv and store the div by getting the element by his id.

InnerText

We start with InnerText and call it into myDiv variable who contain the div element .

myDiv.innerText// "Hello"

Outcome

innerText applies text-transform and white-space rules and will not return text with invisible items.

It returns the content who is displayed in your web page without any tags , only the text in a string form.

The innerText property sets or returns the text content of the specified node, and all its descendants.

textContent

Now we call .textContent on myDiv variable.

myDiv.textContent// "Hello World"

Outcome

textContent is not aware of styling and will therefore return also content hidden by CSS.

While innerText returns the visible text contained in a node, textContent returns the full text, including the element with a display non style. We get all back without any tags , only the text in a string form.

The textContent property sets or returns the text content of the specified node, and all its descendants.

innerHTML

And the last one, innHTML.

myDiv.innerHTML// "
<span>Hello <span style="display: none;">World</span></span>
"

Outcome

innerHTML is literally retrieves all the HTML content inside the element which we are calling.

It returns the string inside our <div> and the HTML (contained within our string, including any spacing, line breaks, etc.).

Overview

Let’s put all these three properties to have a better view of the thin difference.

myDiv.textContent// "Hello World"myDiv.innerText// "Hello"myDiv.innerHTML// <span>Hello <span style="display: none;">World</span></span>

As we can see, the difference between textContent and innerText is subtle, the first one will return the full text without taking care of the styling when innerText will give back only the one visible in the webpage.

innerHTML by is name is easier to differentiate and literally bring back an HTML content.

--

--

Tosh
Tosh

Written by Tosh

Software Engineering student @Flatiron

No responses yet