At first glance, both properties look like they do the same thing.
While innerHTML provides a simple and convenient way to create HTML templates as strings and inject them into the DOM [Document Object Model], textContent only lets you create plain texts as strings.
Now, let's break it down.
textContent in action:
Say we want to output "I love JavaScript"
<p id="output"></p>
<script>
document.getElementById("output").textContent = "I love Javascript";
</script>
innerHTML in action:
innerHTML can do everything textContent can, plus a higher level of DOM manipulation. For instance;
Let's output "I love JavaScript"
Note: "I" is Italicised, "love" is bold, and let's assume "JavaScript" is in red
<p id="output"></p>
<script>
document.getElementById("output").innerHTML = "<em>I</em> <strong>love</strong> <span style='color: red;'>JavaScript</span>";
</script>
Conclusion:
innerHTML is richer, as you can get more fanciful with it.
But if you only aim to return text content, go ahead with textContent.
Hope you find this helpful.
Happy to learn from you.
How would you use these properties?
Top comments (7)
innerHTMLis a security hole.(
Along with not being a standard- it turns out that is is part of the HTML5 standard).Hmmm!
Cross-site scripting vulnerabilities.
I agree
innerHTMLis not completely safe in all use cases, it can still be used in some circumstances, such as inserting static data on a page where user input is not collected!Curious, what would you use instead?
Project Trusted Types, for example, prevents (not completely though, allows custom sanitizers) the use of
innerHTML.The alternative is very simple (although somewhat more verbose):
document.createElement()andappendChild()etc..Even better and faster are document fragments.
XO linter changes
innerTexttotextContentautomatically.Not sure what you mean.
Saying there's a way to chain both properties to achieve the same result?