loading...

textContent VS innerText

mohananagavenkat profile image Mohana Naga Venkat Sayempu ・1 min read

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 πŸ˜€

Discussion

pic
Editor guide
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 Author

Cool πŸ˜ƒ. Great to know that, Thanks 😊