My friend Chris Ferdinandi has already written about the difference between the
textContent properties. Today, I want to show you the difference between the
The MDN Web Docs explain that the
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
In the following HTML snippet, I'm using the
hidden attribute to hide the second paragraph:
<p>This paragraph is visible.</p>
<p hidden>This paragraph is hidden.</p>
Assume I've selected the
var div = document.querySelector("div");
...and I'm inspecting the properties of that element:
Here's what the
textContent property shows:
"\n This paragraph is visible.\n This paragraph is hidden.\n"
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:
- Escape notation for new lines (
- The hidden paragraph
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.
There's a fantastic summary in the MDN Web Docs:
textContentgets the content of all elements, including
<style>elements. In contrast,
innerTextonly shows “human-readable” elements.
textContentreturns every element in the node. In contrast,
innerTextis aware of styling and won’t return the text of “hidden” elements.
- Moreover, since
innerTexttakes CSS styles into account, reading the value of
innerTexttriggers a reflow to ensure up-to-date computed styles. (Reflows can be computationally expensive, and thus should be avoided when possible.)
innerTextin 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: