Home >Web Front-end >JS Tutorial >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>
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:
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";
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!