HomeJAVASCRIPTDifference between innerHTML, innerText, and textContent.

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:none or visibility: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 innerText because 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

PropertyIncludes HTML?Hidden text?PerformanceUse Case
innerHTMLβœ… Yesβœ… YesMediumWhen you need HTML structure
innerText❌ No❌ NoSlowerWhen you need visible text only
textContent❌ Noβœ… YesFasterWhen 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).

Share:Β 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *