Understanding innerText, innerHTML, and textContent in JavaScript

Abhinay JangdeAbhinay Jangde
2 min read

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

video

#πŸ’‘ 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.

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