DEV Community

Ashiqur Rahman
Ashiqur Rahman

Posted on

Difference between innerText, textContent, innerHtml and outerHtml

Often we need to extract the text from Html elements. but
sometimes we are puzzled about the difference between them. let's tackle them now. this is our html element:

<h2>
   Sub Div
   <span>I am hidden</span>
</h2>

we want to, extract the text part of the above element. let's write some javascript(basically dom-manipulation),

const heading = document.querySelector('h2');
console.log(heading.textContent);
console.log(heading.innerText);

You can see in the browser console. both outputs are almost the same (the one which uses 'textContent' is not trimmed properly)

screenshot

So, what is the difference between them? For example, we add a style tag inside h2 element.

<h2>
   Sub Div
   <style>
      h2 {
      background-color: orangered;
      }
   </style>
   <span>I am hidden</span>
</h2>

now if you console.log again. you will get this as output

screenshot-1

We are seeing that the textContent is giving the whole style element along with text and innerText is giving us the human-readable text.

There is another useful difference between them. suppose we hidden the visibility of an element by applying css rules and then try to extract them.

<head>
   <style>
      h2 span {
      display: none;
      }
   </style>
   <head>
<body>
   <h2>
      Sub Div
      <span>I am hidden</span>
   </h2>
</body>

Now let's take a look what console.log gives us:

screenshot-2

We are seeing that textContent does not care about the css rules but innerText does. So, textContent would be handy If we need to get the text of an element that is hidden by CSS. 😉

The other two techniques are innerHtml and outerHtml. I think if we see the output in browser console we will understand them easily as they are pretty self-explanatory.

const heading = document.querySelector('h2');
console.log(heading.innerHTML);
console.log(heading.outerHTML);

let's see the output in the browser cosnole

screenshot-4

Top comments (1)

Collapse
 
naimur profile image
Naimur Rahman

I was using textContent most of the time to extract. But didn't know this shouldn't be used everywhere. Thanks