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 😀
Top comments (5)
Another one is
.textContent = ''
is the fastest way to delete all children nodes.That's a nice tip~ Thank you, Pacharapol~
Cool 😃. Great to know that, Thanks 😊
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.
What is the difference between innerText and outerText? Kauri Kamakhya Tantrik