DEV Community

Mohana Naga Venkat Sayempu
Mohana Naga Venkat Sayempu

Posted on

19 2

textContent VS innerText

I used to think that there is no difference between textContent and innerText. But today I came to know that there exist some important differences between them.

i) textContent gets the content of all elements, including <script> and <style> elements. In contrast, innerText only shows human-readable elements.

Example:-
HTML

<p>
    some paragraph text
    <style>
      p {
        color: red;
      }
    </style>
</p>

JS

const p = document.querySelector('p');
console.log(p.textContent);
/* textContent returns the content inside style, script elements as well..Above statement logs:
  Some textSome Other Text

  p {
    color: red;
  }
*/
console.log(p.innerText);
/* innerText returns only human-readable elements. Above statement logs:
  Some textSome Other Text
*/

ii) textContent returns every element in the node. In contrast, innerText is aware of styling and won't return the text of hidden elements.

Example:-
HTML

<style>
.special {
      display: none;
    }
</style>
<h1>Heading <span class="special">Special</span> </h1>
const h1 = document.querySelector('h1');
console.log(h1.textContent);
/* textContent is not aware of styles. So it returns entire content. Above statement logs:
Heading Special
*/
console.log(h1.innerText);
/* innerText is aware of css, doesn't return hidden content. Above statement logs:
Heading
*/

Happy Coding 😀

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (5)

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

Another one is .textContent = '' is the fastest way to delete all children nodes.

Collapse
 
dance2die profile image
Sung M. Kim

That's a nice tip~ Thank you, Pacharapol~

Collapse
 
mohananagavenkat profile image
Mohana Naga Venkat Sayempu

Cool 😃. Great to know that, Thanks 😊

Collapse
 
moshgo profile image
Moshe Goldstein

Thank you. I came across these two options in my bootcamp, and they recommended finding a blog that explains it. You've done a great job.

Collapse
 
monikavogler profile image
MonikaVogler

What is the difference between innerText and outerText? Kauri Kamakhya Tantrik

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please show some love ❤️ or share a kind word in the comments if you found this useful!

Got it!