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).
