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:
Hello
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".
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3