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

textContent vs innerText: Which Should You Use?

Mary-Kate Olsen
Release: 2024-11-17 01:53:03
Original
192 people have browsed it

textContent vs innerText: Which Should You Use?

textContent vs innerText: Exploring the Differences in JavaScript

In JavaScript, retrieving the textual content of HTML elements has two primary options: textContent and innerText. While they may seem similar at first glance, there are subtle but important distinctions between the two.

innerText vs textContent

Kelly Norton's blogpost (https://blog.kellynorton.com/2009/07/10/whats-the-difference-between-innertext-and-textcontent/) provides a comprehensive overview of the differences:

  • Origin and Standardization: innerText was initially introduced as a non-standard property, while textContent was subsequently standardized.
  • Returned Text Content: innerText retrieves the visible text displayed within an element, excluding elements with display: none or other visibility modifiers. In contrast, textContent retrieves the complete textual content, including hidden or inaccessible parts.
  • Performance Considerations: Due to its dependence on layout information, innerText is more resource-intensive compared to textContent.
  • Object Compatibility: innerText is only defined for HTMLElement objects, while textContent is defined for all Node objects.

Usage Considerations

As illustrated in your example:

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

Using textContent is an acceptable method for setting the textual content of an element. It will effectively change the visible text and any hidden content within that element.

However, it's important to note that, if compatibility with older browsers like IE8 is essential, a bare-metal polyfill may be required to implement textContent functionality.

The above is the detailed content of textContent vs innerText: Which Should You Use?. 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