DEV Community

Cover image for JavaScript DOM - Part 4 - innerHTML vs innerText vs textContent [video + article]
Tharun Shiv
Tharun Shiv

Posted on • Updated on

 

Textcontent vs Innerhtml JavaScript DOM - Part 4 - innerHTML vs innerText vs textContent [video + article]

This is going to be a multi-part Video + article tutorial series on JavaScript DOM. You're reading Part 4

You can read Part 3 here:

innerText | innerHTML | textContent

All three of them are attributes that you can get from the elements. They are not the same and we will be looking at how they are different with the below illustrations.

innerText

When applied to an element, it returns only the text which is inside the element, the text part wrapped by the element and nothing else, it also ignores the space.

syntax:

element.innerText
Enter fullscreen mode Exit fullscreen mode

example:

<p id="experiment">
  <br />
  Hello this is <span>Tharun</span> How are you?
  <br />
</p>
Enter fullscreen mode Exit fullscreen mode
let p = document.getElementById('experiment');
console.log(p.innerText)
Enter fullscreen mode Exit fullscreen mode

output

"
Hello this is Tharun How are you?
"
Enter fullscreen mode Exit fullscreen mode

innerHTML

When applied to an element, it returns the text part enclosed by the element, along with the HTML tags inside, and also considers the spacing given inside. Look at the example below.

syntax:

element.innerHTML
Enter fullscreen mode Exit fullscreen mode

example:

<p id="experiment">
  <br />
  Hello this is <span>Tharun</span> How are you?
  <br />
</p>
Enter fullscreen mode Exit fullscreen mode
let p = document.getElementById('experiment');
console.log(p.innerHTML)
Enter fullscreen mode Exit fullscreen mode

output

"
  <br>
  Hello this is <span>Tharun<span/> How are you?
  <br>
"
Enter fullscreen mode Exit fullscreen mode

textContent

When applied to an element, it returns the text part enclosed by the element and considers the spacing given inside. Look at the example below.

syntax:

element.textContent
Enter fullscreen mode Exit fullscreen mode

example: