有没有办法得到只有顶层元素的innerText(并忽略子元素的innerText)? [英] Is there a way to get innerText of only the top element (and ignore the child element's innerText)?

查看:512
本文介绍了有没有办法得到只有顶层元素的innerText(并忽略子元素的innerText)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



示例:


$有一种方法来获取只有顶级元素的innerText(并忽略子元素的innerText) b $ b

 < div> 
顶级节点文本
< div>子节点文本< / div>
< / div>

如何获取顶级节点文本,同时忽略子节点文本?顶层div的innerText属性似乎返回了内部和顶部文本的连接。

解决方案

只需遍历子节点并连接文本节点:

  var el = document.getElementById(your_element_id),
child = el.firstChild,
texts = [];

while(child){
if(child.nodeType == 3){
texts.push(child.data);
}
child = child.nextSibling;
}

var text = texts.join();


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.

解决方案

Just iterate over the child nodes and concatenate text nodes:

var el = document.getElementById("your_element_id"),
    child = el.firstChild,
    texts = [];

while (child) {
    if (child.nodeType == 3) {
        texts.push(child.data);
    }
    child = child.nextSibling;
}

var text = texts.join("");

这篇关于有没有办法得到只有顶层元素的innerText(并忽略子元素的innerText)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆