javascript检查子节点是否为元素或文本节点 [英] javascript check if child node is element or text node
本文介绍了javascript检查子节点是否为元素或文本节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 childNodes
的问题,如下所示:
i have problem with childNodes
as below :
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ol>
//childNodes.length = 7
但是
<ol><li> Coffee </li><li> Tea </li><li> Coca Cola </li></ol>
//childNodes.length = 3
似乎每个 \\ \\ n
或 textnode
被视为子
,如何从<$中删除这些c $ c> childNodes ?
It seems each \n
or textnode
is considered a child
,how can i remove these from childNodes
?
推荐答案
您可以检查给定子节点是否为文本节点或不使用 nodeType
。文本节点的 nodeType
为 3
。我们可以使用该号码或常量节点。 TEXT_NODE
用于检查。
You can check if a given child node is a text node or not using the nodeType
. Text nodes will have the nodeType
as 3
. We can either use the number or the constant Node.TEXT_NODE
for checking.
window.onload = function() {
var el = document.getElementsByTagName('ol')[0].childNodes; // using [0] as there is only one ol in the demo
console.log('Print with text nodes');
for (var i = 0; i < el.length; i++) { // will output all nodes with "undefined" for text nodes
console.log(el[i].innerHTML);
}
console.log('Print without text nodes');
for (var i = 0; i < el.length; i++) { // will output only non text nodes.
if (el[i].nodeType != Node.TEXT_NODE) // or if (el[i].nodeType != 3)
console.log(el[i].innerHTML);
}
}
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ol>
这篇关于javascript检查子节点是否为元素或文本节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文