Understanding innerText, innerHTML, and textContent in JavaScript


When working with the DOM (Document Object Model) in JavaScript, you often need to read or change the content of HTML elements.
But wait... there are three similar-sounding properties:
innerText
innerHTML
textContent
They may look the same, but they behave differently in important ways. Letβs break them down with examples and a fun analogy. π
π― 1. element.innerText
β What it does:
innerText
returns the visible text content of an element β what a user actually sees on the screen. It ignores hidden elements (like those with display: none
) and respects CSS styles (like text-transform
).
π§ Example:
<div id="box1">Hello <span style="display:none">World</span></div>
<script>
const box1 = document.getElementById("box1");
console.log(box1.innerText); // Output: Hello
</script>
Since the <span>
is hidden, innerText
ignores it.
π― 2. element.innerHTML
β What it does:
innerHTML
returns the HTML code (tags + content) inside the element. You can also set it to insert new HTML.
π§ Example:
<div id="box2">Hello <b>World</b></div>
<script>
const box2 = document.getElementById("box2");
console.log(box2.innerHTML); // Output: Hello <b>World</b>
</script>
You get the HTML structure, not just the text.
π― 3. element.textContent
β What it does:
textContent returns the raw text inside the element β even hidden text. It doesn't care about CSS or visibility.
π§ Example:
<div id="box3">Hello <span style="display:none">World</span></div>
<script>
const box3 = document.getElementById("box3");
console.log(box3.textContent); // Output: Hello World
</script>
π When to Use What?
β Use innerText β When you care about whatβs visible to the user.
β Use innerHTML β When you want to read or write HTML code.
β Use textContent β When you want to get all the text, no matter if itβs hidden.
video to understand clearly
#π‘ Pro Tip: Avoid using innerHTML with user input to prevent XSS (Cross-site scripting) attacks.
I hope this blog post helped you clearly understand the differences between innerText, innerHTML, and textContent.
Subscribe to my newsletter
Read articles from Abhinay Jangde directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Abhinay Jangde
Abhinay Jangde
I am finay year engineering student.