Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve innerText of hidden element

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/

like image 310
powerbuoy Avatar asked May 02 '17 14:05

powerbuoy


People also ask

How do I get hidden text elements?

In some cases, one may find it useful to get the hidden text, which can be retrieved from element's textContent , innerText or innerHTML attribute, by calling element. attribute('attributeName') . element. getAttribute("textContent") worked for me.

What does innerText return?

The innerText property returns: Just the text content of the element and all its children, without CSS hidden text spacing and tags, except <script> and <style> elements. The textContent property returns: The text content of the element and all descendaces, with spacing and CSS hidden text, but without tags.

Is innerText always a string?

OpenXML- InnerText is always an Integer and not a String.

What does innerText mean?

The innerText property of the HTMLElement interface represents the rendered text content of a node and its descendants. As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied it to the clipboard.


1 Answers

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.

like image 106
adeneo Avatar answered Oct 28 '22 18:10

adeneo