Home > Web Front-end > JS Tutorial > body text

innerText vs textContent: When Should You Use Each?

Mary-Kate Olsen
Release: 2024-11-10 00:08:02
Original
680 people have browsed it

innerText vs textContent: When Should You Use Each?

textContent vs innerText: Which One to Use?

innerText and textContent are two commonly used properties in JavaScript for accessing the text content of elements. While both properties share similar functionality, there are key differences that determine the appropriate use case for each.

innerText

innerText returns the visible text contained within an HTML element. It excludes any hidden elements or elements with display styles set to 'none'.

Example:

<p>Hello <span>
Copy after login

innerText would return 'Hello' for this element.

textContent

textContent, on the other hand, returns the full text content, regardless of visibility or display styles. In the above example, textContent would return 'Hello World'.

Key Differences:

  • Standard Compliance: innerText was a non-standard property, whereas textContent is a standardized property.
  • Performance: innerText requires layout information to determine visible text, making it more performance-intensive than textContent.
  • Scope: innerText is only available for HTMLElement objects, while textContent can be used with all Node objects.

Usage Considerations:

For cases where you want to access only the visible text, innerText may be a more efficient choice. However, if you need to retrieve the entire text content, включая скрытый контент, textContent is the preferred property.

In the provided example:

var logo$ = document.getElementsByClassName('logo')[0];
logo$.textContent = "Example";
Copy after login

You can use textContent to update the text content of the logo element. It will replace any existing text with "Example".

The above is the detailed content of innerText vs textContent: When Should You Use Each?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template