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.

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

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!

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Dive into this insightful write-up, celebrated within the collaborative DEV Community. Developers at any stage are invited to contribute and elevate our shared skills.

A simple "thank you" can boost someone’s spirits—leave your kudos in the comments!

On DEV, exchanging ideas fuels progress and deepens our connections. If this post helped you, a brief note of thanks goes a long way.

Okay