检索隐藏元素的 innerText
Retrieve innerText of hidden element
我正在尝试获取元素的 innerText
但 Chrome returns 是一个空字符串,因为我的元素被隐藏了。
Firefox 没有。
有没有办法在 Chrome 中检索 innerText
,即使该元素不可见?
console.log(document.querySelector('div').innerText + ':' + document.querySelector('div').innerHTML);
div {
height: 0;
overflow: hidden;
}
<div>
Hello, I'm <strong>empty!</strong>
</div>
老实说,我真的很惊讶 Chrome 这样的行为,这是一个错误吗?
你想为此使用 textContent
,因为它 return 来自隐藏元素的文本
document.querySelector('div').textContent
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.
这不是 Chrome 错误,而是 Firefox 错误,innerText
不应该 return 隐藏元素的内容。
innerText
在所有浏览器上都是 not well supported。
以下是支持 innerText 的浏览器。
我正在尝试获取元素的 innerText
但 Chrome returns 是一个空字符串,因为我的元素被隐藏了。
Firefox 没有。
有没有办法在 Chrome 中检索 innerText
,即使该元素不可见?
console.log(document.querySelector('div').innerText + ':' + document.querySelector('div').innerHTML);
div {
height: 0;
overflow: hidden;
}
<div>
Hello, I'm <strong>empty!</strong>
</div>
老实说,我真的很惊讶 Chrome 这样的行为,这是一个错误吗?
你想为此使用 textContent
,因为它 return 来自隐藏元素的文本
document.querySelector('div').textContent
TextContent
differs frominnerText
...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, whereastextContent
will.As
innerText
is aware of CSS styling, it will trigger a reflow, whereastextContent
will not.
这不是 Chrome 错误,而是 Firefox 错误,innerText
不应该 return 隐藏元素的内容。
innerText
在所有浏览器上都是 not well supported。
以下是支持 innerText 的浏览器。