The textContent and innerText properties in vanilla JS

My friend Chris Ferdinandi has already written about the difference between the innerHTML and textContent properties. Today, I want to show you the difference between the textContent and innerText properties.

The MDN Web Docs explain that the innerText property approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied it to the clipboard.

The main difference is that innerText is aware of the rendered appearance of text, while textContent is not.

An example

In the following HTML snippet, I’m using the hidden attribute to hide the second paragraph:

<div>
  <p>This paragraph is visible.</p>
  <p hidden>This paragraph is hidden.</p>
</div>

Assume I’ve selected the div

var div = document.querySelector("div");

…and I’m inspecting the properties of that element:

div.textContent;

div.innerText;

The textContent property

Here’s what the textContent property shows:

"\n  This paragraph is visible.\n  This paragraph is hidden.\n"

The innerText property

And here’s what the innerText property shows:

"This paragraph is visible."

What’s the difference?

As you can see, the textContent property has picked up the exact text content inside the div. It’s showing all the text, including:

The innerText property is only concerned with the rendered text the user will actually see. In this case, that’s the text inside the first paragraph element. It has stripped out eveything except the visible text.

Summary

There’s a fantastic summary in the MDN Web Docs:

  • textContent gets the content of all elements, including <script> and <style> elements. In contrast, innerText only shows “human-readable” elements.
  • textContent returns every element in the node. In contrast, innerText is aware of styling and won’t return the text of “hidden” elements.
    • Moreover, since innerText takes CSS styles into account, reading the value of innerText triggers a reflow to ensure up-to-date computed styles. (Reflows can be computationally expensive, and thus should be avoided when possible.)
  • Unlike textContent, altering innerText in Internet Explorer (version 11 and below) removes child nodes from the element and permanently destroys all descendant text nodes. It is impossible to insert the nodes again into any other element or into the same element after doing so.

I always default to the textContent property. I don’t think I’ve ever actually used the innerText property in a real application. I’m not saying you shouldn’t, but it’s good to be aware of which is more appropriate.

For more information, check out the following resources:


If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!