Hey everyone!
If you’re working with JavaScript and trying to get or change content inside HTML elements, you’ve probably come across these three:
innerText, innerHTML, and textContent.
They might look similar — but they work differently!
Let’s go through them one by one with simple examples so you can see exactly what each one does.
1. innerText
innerText gives you the text you can actually see on the screen. It hides anything that’s not visible (like elements with display: none) and respects line breaks and formatting.
html
<p id="demo1">Hello <span style="display:none;">Hidden</span> World</p>
js
const result = document.getElementById("demo1").innerText;
console.log(result); // Output: "Hello World"
2. innerHTML
innerHTML gives you everything inside an element — not just the text, but also the HTML tags.
html
<p id="demo2">Hello <strong>World</strong></p>
js
const result = document.getElementById("demo2").innerHTML;
console.log(result); // Output: "Hello <strong>World</strong>"
3. textContent
textContent gives you all the text, even from elements that are hidden — but it doesn’t include any HTML tags.
html
<p id="demo3">Hello <span style="display:none;">Hidden</span> World</p>
js
const result = document.getElementById("demo3").textContent;
console.log(result); // Output: "Hello Hidden World"
Which One Should You Use?
- Use innerText if you want only what’s visible on the page.
- Use innerHTML if you need to get or set HTML code.
- Use textContent if you want plain text, including what’s hidden.
That’s All!
Now you won’t mix them up again! Next time you're dealing with the DOM, you’ll know exactly which one to choose — depending on whether you want HTML, visible text, or raw content.
Top comments (0)