Difference Between innerText, textContent, and innerHTML
innetText Retrieves or sets the visible text of an element, ignoring any hidden content. It only includes text that is shown to the user.
When working with web pages in JavaScript, you often need to get or change the content of elements. There are three main properties you can use: innerText
, textContent
, and innerHTML
. Each one behaves differently, so let’s look at what they do and how they’re different.
1. innerText
What it does: Retrieves or sets the visible text of an element, ignoring any hidden content.
Key Point: It only includes text that is shown to the user (ignores elements with
display: none
orvisibility: hidden
).Use it when: You want to get or change the text that is actually visible on the page.
<div id="example">
<p>Hello <span style="display:none;">World</span>!</p>
</div>
<script>
const element = document.getElementById('example');
console.log(element.innerText); // Output: "Hello !"
</script>
2. textContent
What it does: Retrieves or sets all the text inside an element, including text from hidden elements, but without any HTML tags.
Key Point: It gives you all the text, even if some of it is hidden (e.g.,
display: none
elements).Does not trigger reflow: Since it does not involve recalculating the page layout,
textContent
is faster thaninnerText
.Use it when: You want to get or change all the text, regardless of whether it's visible or hidden, and you don’t care about HTML tags.
<div id="example">
<p>Hello <span style="display:none;">World</span>!</p>
</div>
<script>
const element = document.getElementById('example');
console.log(element.textContent); // Output: "Hello World!"
</script>
3. innerHTML
What it does: Retrieves or sets the HTML content of an element, including both text and HTML tags.
Key Point: It includes everything inside the element—text and HTML tags.
Modifies HTML structure: You can set
innerHTML
to update or replace the entire content of an element, including adding new HTML tags or structures.Potential security risks: Setting
innerHTML
from untrusted sources can expose your application to Cross-Site Scripting (XSS) attacks, so you need to sanitize inputs.Use it when: You want to get or change the entire HTML structure, not just the text.
<div id="example">
<p>Hello <span>World</span>!</p>
</div>
<script>
const element = document.getElementById('example');
console.log(element.innerHTML);
// Output: "<p>Hello <span>World</span>!</p>"
</script>
Quick Comparision
Property | Includes HTML Text? | Includes HTML Tags? | When to Use it |
innerText | No | No | For Visible text only |
textContent | Yes | No | For all text, hidden or visible |
innerHTML | Yes | Yes | For Full HTML, including tags |
Summary:
Use
innerText
for visible text.Use
textContent
for all text, including hidden content.Use
innerHTML
to access or modify the entire HTML, including tags and structure.