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>
Example of textContent
We have passed a string "Hello World" as the textual content of h2
.
document.getElementById("textContent").textContent = "Hello World";
Here, passing any HTML tags as a string won't render as HTML.
Output
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>";
Output
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)
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).
Thank you for sharing these insights! :)
Insightful, thanks!