Many times you have to use methods such as ".textContent", ".innerHTML", ".innerText" and you really don't know why are there so many methods for the same thing. But, wait! there is a difference in all these and each term has its specific use that we are going to discuss in this blog.
Let's get started
.innerText | .innerHTML | .textContent
We will understand all these with the help of examples.
Let's say we have an element that is as follows:
<body>
<div id="myDiv">
<p>This is a paragraph</p>
</div>
</body>
Now, let us try to grab the content of myDiv using these three methods and see the difference.
First, with innerText
const myDiv = document.getElementById('myDiv');
const content = myDiv.innerText;
//By console log let see what is stored in the content
console.log(content)
.innerText is giving us only the text present inside the myDiv
Let's try what is the case with .textContent
const content = myDiv.textContent;
//By console log let see what is stored in the content
console.log(content)
Can you see the space before the paragraph? Before answering all this let's also watch what .innerHTML return.
const content = myDiv.innerHTML;
//By console log let see what is stored in the content
console.log(content)
(Wait! wait! wait! 😮
What the hell is happening here? Now, this is returning something different. I am out of my mind 🤐)
Don't get confused. Let me tell you what just happened:
innerText
This method only returns the text content of the element and not any other thing. You can also set the text of the element by using this but you can't alter any other thing rather than the text.
textContent
This method not only returns the text but also all the descendants of the element and spaces that you can see in the screenshot above.
.innerHTML👑
As you can see in the screenshot the .innerHTML not only returns the text and not only returns the spaces that are present there but also returns the tags present over there in the element.
Thank you for reading