DEV Community

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

Posted on

6

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.

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

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!

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay