The Subtle Differences between 'innerText' and 'textContent' You Should Know
Valencia White
Posted on February 17, 2022
While both properties on the surface seem to perform the same task within lines of code - render the text from an element or tag. Understanding the similarities and differences between the two will allow you to choose the property optimal for your next JavaScript project.
Element.innerText
Where 'element.innerText' triumphs above the other property, is the fact innerText takes into account CSS styling. Opting for rendering what humans prefer to read. Text will be rendered in plain text. Keeping styling in mind, 'element.innerText' trims all white space in its renderings, unlike 'node.textContent'.
To better demonstrate what '.innerText' does, below there's a sample of HTML.
<div id='property-test'>
Flatagram is the <strong>best</strong> app ever! Wouldn't <em>you</em> agree?
</div>
Once opened in browser, the code renders a sentence of "Flatagram is the best app ever! Wouldn't you agree?" with strong/bold tags wrapped around "best" and em/italic tags wrapped around "you".
const renderText = document.getElementById('property-test');
I assigned the div to a new variable. Let's call .innerText on our new variable 'renderText'.
renderText.innerText
// => Flatagram is the best app ever! Wouldn't you agree?
Once called, what's rendered is plain text. No inclusion of HTML tags like '.innerHTML' and no inclusion of the spacing like '.textContent'.
Node.textContent
Node.textContent triumphs 'element.innerText' in the event, all elements in the node need to be rendered.
<div id="market-options">
<div>mangos, coconuts, and pears</div>
<div style="visibility:hidden">all go great in a smoothie bowl.</div>
</div>
In the code above although we have a element set to be hidden, using '.textContent' will override the assigned setting and display as logged.
mangos, coconuts, and pearsall go great in a smoothie bowl.
Conclusion
After reading through this post, I hope you've learned something new about .innerText and .textContent properties. And because I know one source is never enough to encapsulate the depth of knowledge that programming entails, I highly encourage you to check out the extra resources I've provided to show you more examples of the nuances of these properties and how they affect your code.
Resources
Posted on February 17, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.