DEV Community

Cover image for The Subtle Differences between 'innerText' and 'textContent' You Should Know
Valencia White
Valencia White

Posted on • Updated on

The Subtle Differences between 'innerText' and 'textContent' You Should Know

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>
Enter fullscreen mode Exit fullscreen mode

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".

Browser render of code above

const renderText = document.getElementById('property-test');
Enter fullscreen mode Exit fullscreen mode

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?

Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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

  • More information on .innerText Property | link
  • Comparison of the properties | link

  • MDN .textContent | link

Top comments (0)