Difference between innerText and textContent methods in JavaScript
The `innerText` and `textContent` methods in JavaScript are used to interact with the text inside HTML elements, but they have key differences:
1. innerText:
- Reflects the *visible text* of an element, taking into account CSS styles like `display: none` or `visibility: hidden`.
- Triggers a reflow to ensure it returns the text as it appears on the screen.
- Ignores hidden or non-visible content.
2. textContent:
- Retrieves or sets all the text inside an element, regardless of visibility or CSS properties.
- Does not trigger a reflow, making it faster and more efficient.
- Includes hidden text within the element.
Here’s a simple example:
```html
<div id="example" style="display:none;">Hello, World!</div>
```
```javascript
let element = document.getElementById("example");
console.log(element.innerText); // Output: (empty string, as the div is hidden)
console.log(element.textContent); // Output: "Hello, World!" (includes all text, hidden or not)
```
Use `innerText` when you're concerned with visible content, and `textContent` for the full raw text.
Comments
Post a Comment
Write something to CodeWithAbdur!