innerText vs innerHTML

Prashant HandelPrashant Handel
2 min read

What is innerText?

The innerText method is used to get the text within the text excluding the tag itself. It avoids the tags within it and only return the text values in the form of the string.

For example

<div id="HelloAll">Hello All
            <span><b>I am Prashant</b></span>
        </div>

Calling innerText method on the div having id HelloAll

HelloAll.innerText

Output is

innerText method can also modify text within the elements.

HelloAll.innerText = "Hello All I am Prashant";

Output

What is innerHTML?

The innerHTML is a DOM element method that is used to get the whole content which is inside the element on which this method is applied. It doesn't return the element on which this method is called but only gives out whole text content within it in the form of a string.

Let's take an example-

<p id="para">Hi! <b> I am Prashant</b></p>

We can call innerHTML method on the p tag by using its id in this way.

para.innerHTML    // Hi! <b> I am Prashant</b>

We not only get the innerHTML but also modify it by assigning the value to it, for example

para.innerHTML = `Hi! I am Rohan`;

In the above assignment, I changed the name from Prashant to Rohan and also removed the bold tag.

Conclusion

The innerText and innerHTML methods are much similar to each other. The innerHTML includes the text as well as tags within the element. But the innerText method includes the tags and ignores the tags within it.

1
Subscribe to my newsletter

Read articles from Prashant Handel directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Prashant Handel
Prashant Handel

I'm a self taught web developer and a learner as well. I am sharing my experiences and knowledge here with a hope to help those who are beginners as sharing helps to grow together.