DEV Community

Cover image for Difference between innerText and textContent in HTML
Madhu Saini
Madhu Saini

Posted on

Difference between innerText and textContent in HTML

innerText

innerText retrieves or sets the text content of an element and all its descendants, and it is aware of the current styling applied to the elements. This means that if there are any styles applied to an element that hide it (like display: none), innerText will not return the text content of that element.

Here's an example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>innerText Example</title>
</head>
<body>
  <div id="exampleDiv">
    This is some <span style="display: none;">hidden</span> text.
  </div>

  <script>
    const div = document.getElementById('exampleDiv');
    console.log(div.innerText); // Output: This is some text.
  </script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode


html

Image description

In this example, innerText returns only the visible text inside the #exampleDiv element, ignoring the hidden span.

textContent

textContent returns the text content of all elements, including hidden elements or those with visibility set to hidden. It doesn't consider CSS styling and simply returns all text contained within the specified element.

Here's an example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>textContent Example</title>
</head>
<body>
  <div id="exampleDiv">
    This is some <span style="display: none;">hidden</span> text.
  </div>

  <script>
    const div = document.getElementById('exampleDiv');
    console.log(div.textContent); // Output: This is some hidden text.
  </script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

In this example, textContent returns all the text within #exampleDiv, including the text inside the hidden span.

Conclusion

  • Use innerText when you want to retrieve only the visible text content of an element, considering CSS styles.
  • Use textContent when you want to retrieve all text content within an element, regardless of CSS styling or visibility.

If you liked this blog, please share it with others who might find it useful. You can also keep up with me for more stuff about JavaScript, React, Next.js, MongoDB & Web Development.

You can find me on Twitter, LinkedIn, and GitHub.

Thanks for reading🌻

Top comments (0)