有没有办法只获取顶部元素的innerText(并忽略子元素的innerText)?
有没有办法只获取顶部元素的innerText(并忽略子元素的innerText)?
示例:
<div>
top node text
<div> child node text </div>
</div>
如何获取“顶部节点文本”而忽略“子节点文本”?顶部 div 的 innerText 属性似乎返回内部文本和顶部文本的串联。
Is there a way to get innerText of only the top element (and ignore the child element's innerText) ?
Example:
<div>
top node text
<div> child node text </div>
</div>
How to get the "top node text" while ignoring "child node text" ? innerText property of top div seem to return concatenation of both inner , top text.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
只需迭代子节点并连接文本节点:
Just iterate over the child nodes and concatenate text nodes:
这将在您的示例中起作用:
document.getElementById("item").firstChild.nodeValue;
这是工作代码片段:
This will work in your example:
document.getElementById("item").firstChild.nodeValue;
Here is working code snippet:
如果元素具有
tagName
属性,则它是一个元素:删除该节点。innerText
获取文本内容(当不支持innerText
时,回退到textContent
)。代码:
If the element has a
tagName
attribute, then it's an element: Remove the node.innerText
to get the textual contents (with fallback totextContent
, wheninnerText
is not supported).Code:
正如所有其他答案已经解释的那样,您需要检查子节点的类型。
这是基于 @ehsaneha 的答案的简洁单行:
或者作为原型方法:
用法:
兼容性参考:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
https://developer.mozilla.org/ en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
https://developer.mozilla.org/ en-US/docs/Web/API/Node/nodeType?retiredLocale=de
As every other answer already explained, you need to check the type of the childnode.
Here is a neat one-liner based on @ehsaneha's answer:
Or as a prototyped method:
usage:
Compatibility reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType?retiredLocale=de
如果您不想忽略子元素的内部文本,请使用以下函数:
If you don't want to ignore the child element's inner text, use the following function: