Reputation: 975
textContent
gets the content of all elements, including<script>
and<style>
elements. In contrast,innerText
only shows "human-readable" elements.
textContent
returns every element in the node. In contrast,innerText
is aware of styling and won't return the text of "hidden" elements.- https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent#differences_from_innertext
So it seems that innerText
should ignore invisible elements, but acutally it doesn't. Why? It seems I misunderstood something.
Example 1
const style = document.querySelector('style');
style.textContent = 'p { color: red; }'; // works
style.innerText = 'p { color: red; }'; // works. But why?
console.log(style.textContent); // works
console.log(style.innerText); // works. But why?
html { font-family: sans-serif; }
<p>foo</p>
Example 2
const invisibleDiv = document.querySelector('div');
console.log(invisibleDiv.innerText); // works. But why?
<div style="display: none;">
invisible div
</div>
Upvotes: 1
Views: 880
Reputation: 781731
The difference only applies to elements that are nested within the element, not the element's text itself.
console.log("outer.textContent:", outer.textContent);
console.log("outer.innerText:", outer.innerText);
console.log("inner.textContent:", inner.textContent);
console.log("inner.innerText:", inner.innerText);
<div id="outer">This is visible <span id="inner" style="display: none;">This is invisible</span></div>
Upvotes: 1
Reputation: 42354
Because the element is still in the DOM at the point in time JavaScript references it.
To force the alert to fail, you need to remove the element with something like .remove()
, and then (attempt to) reference it.
As you can see in the following, even a Promise's resolution still retains the existing .innerText
, as the reference was made before the element was updated. You explicitly need to update the reference:
let invisibleDiv = document.getElementById('alert');
const resolvedProm = Promise.resolve(invisibleDiv.remove());
let thenProm = resolvedProm.then(value => {
console.log(invisibleDiv.innerText); // Still exists
invisibleDiv = document.getElementById('alert');
console.log(invisibleDiv); // No longer exists
return value;
});
<div id="alert">invisible div</div>
Upvotes: 0