21

I'm trying to get an element's innerText but Chrome returns an empty string because my element is hidden.

Firefox does not.

Is there a way to retrieve the innerText in Chrome even if the element is invisible?

console.log(document.querySelector('div').innerText + ':' + document.querySelector('div').innerHTML);
div {
  height: 0;
  overflow: hidden;
}
<div>
Hello, I'm <strong>empty!</strong>
</div>

Honestly I'm really surprised Chrome behaves like this, is it a bug?

https://jsfiddle.net/r8q2znc4/

powerbuoy
  • 12,460
  • 7
  • 48
  • 78

2 Answers2

34

You want to use textContent for this, as it returns text from hidden elements

document.querySelector('div').textContent

The documentation states that

TextContent differs from innerText ...

Internet Explorer introduced node.innerText.
The intention is similar but with the following differences:

While textContent gets the content of all elements, including <script> and <style> elements, innerText does not.

innerText is aware of style and will not return the text of hidden elements, whereas textContent will.

As innerText is aware of CSS styling, it will trigger a reflow, whereas textContent will not.

This is not a Chrome bug, but rather a Firefox bug, innerText shouldn't return the content of hidden elements.

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Thanks :) Will accept as soon as possible. But do you know _why_ Chrome would return an empty string for `innerText` of hidden elements? Just out of curiosity. Edit: Saw you edit, thanks again :D – powerbuoy May 02 '17 at 14:18
  • Note that text `textContent` will also return text contained between ` – gsouf May 12 '21 at 07:39
  • Any idea why .innerText works on my jsfiddle here? https://jsfiddle.net/JaredHess/0jm4tq5p/32/ In my HTML tab, I have three hidden p tags (using style="display:none"). I tested this in both Firefox and Chrome and .innerText returns the same text as .textContent in my jsfildde Console. I usually use Firefox, and so when I ran into this, I thought perhaps it was the Firefox bug you mentioned, but now I'm not sure what's going on. – Jared Oct 29 '21 at 20:17
-2

innerText is not well supported on all browsers.

Here are the browsers which support well innerText.

enter image description here Screenshoted here

Community
  • 1
  • 1
Mistalis
  • 17,793
  • 13
  • 73
  • 97