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 😀

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more