DEV Community

Cover image for JavaScript "textContent" vs "innerHTML"
zaira
zaira

Posted on

JavaScript "textContent" vs "innerHTML"

In JavaScript, both the innerHTML and textContent can be used to manipulate the text inside HTML elements.However, there is a slight difference between the two.

Let's see that difference in this article.

textContent vs innerHTML

textContent is used to set the text between any tag.You pass the text as the string.

Whereas, innerHTML is used to pass any other HTML as the content of an HTML tag.

For the upcoming examples, we will use this HTML

    <h1>Using innerHTML:</h1>
    <h2 id = "innerHTML"></h2>

    <h1>Using textContent:</h1>
    <h2 id = "textContent"></h2>
Enter fullscreen mode Exit fullscreen mode

Example of textContent

We have passed a string "Hello World" as the textual content of h2.

document.getElementById("textContent").textContent = "Hello World";
Enter fullscreen mode Exit fullscreen mode

Here, passing any HTML tags as a string won't render as HTML.

Output

Image description

Example of innerHTML

Here, we passed some additional HTML <em>Hello World</em> in between the h2 tags. That is why we got the output in italics

document.getElementById("innerHTML").innerHTML = "<em>Hello World</em>";

Enter fullscreen mode Exit fullscreen mode

Output

Image description

Wrapping up

I hope you found this tutorial helpful. Thank you for reading till the end.

I would love to connect with you on any of these platforms.

Top comments (3)

Collapse
 
giovannimazzuoccolo profile image
Giovanni Mazzuoccolo

Nice article!
With textContent and with innerHTML you can also fetching the content (useful for advanced searching).

Be careful with innerHTML, because it is not sanitised. If you want to inject html code, you can use setHTML (not available yet on Firefox by the way).

Collapse
 
hira_zaira profile image
zaira

Thank you for sharing these insights! :)

Collapse
 
crispin_r profile image
Crispin

Insightful, thanks!