Difference between innerHTML, innerText, and textContent.
These three properties in JavaScript are often confused because they deal with reading and writing content inside an element, but they behave differently.
🔹 1. innerHTML
- Returns or sets the HTML markup + text inside an element.
- It parses HTML tags and renders them as elements.
- Security risk: If you insert untrusted input, it can lead to XSS (Cross-Site Scripting).
<div id="box"><b>Hello</b> World</div>
<script>
console.log(document.getElementById("box").innerHTML);
// Output: <b>Hello</b> World
document.getElementById("box").innerHTML = "<i>Hi!</i>";
// The <i> tag is rendered as italic text
</script>
✅ Use when you need HTML inside the element.
🔹 2. innerText
- Returns or sets the visible text inside an element.
- It ignores hidden text (like
display:noneorvisibility:hidden). - It triggers reflow (slower, because it considers styles and layout).
<div id="box">
<span style="display:none">Hidden</span>
Hello <b>World</b>
</div>
<script>
console.log(document.getElementById("box").innerText);
// Output: "Hello World" (hidden span ignored)
document.getElementById("box").innerText = "New Text";
// Only text is inserted (no HTML parsing)
</script>
✅ Use when you want the actual visible text on the page.
🔹 3. textContent
- Returns or sets the all text inside an element (including hidden text).
- It does not parse HTML (tags are treated as plain text).
- Faster than
innerTextbecause it doesn’t trigger reflow.
<div id="box">
<span style="display:none">Hidden</span>
Hello <b>World</b>
</div>
<script>
console.log(document.getElementById("box").textContent);
// Output: "Hidden Hello World" (includes hidden text)
document.getElementById("box").textContent = "<i>Plain Text</i>";
// Output displayed literally as "<i>Plain Text</i>"
</script>
✅ Use when you just want raw text without HTML parsing.
🔑 Quick Comparison Table
| Property | Includes HTML? | Hidden text? | Performance | Use Case |
|---|---|---|---|---|
| innerHTML | ✅ Yes | ✅ Yes | Medium | When you need HTML structure |
| innerText | ❌ No | ❌ No | Slower | When you need visible text only |
| textContent | ❌ No | ✅ Yes | Faster | When you need all raw text |
👉 If I had to summarize:
- innerHTML → Use for HTML.
- innerText → Use for what the user sees.
- textContent → Use for raw text (faster).
No comments yet! You be the first to comment.
