javascript javascript检查子节点是元素还是文本节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24971177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript check if child node is element or text node
提问by talkhabi
i have problem with childNodes
as below :
我有以下问题childNodes
:
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ol>
//childNodes.length = 7
but
但
<ol><li> Coffee </li><li> Tea </li><li> Coca Cola </li></ol>
//childNodes.length = 3
It seems each \n
or textnode
is considered a child
,how can i remove these from childNodes
?
似乎每个\n
或被textnode
认为是一个child
,我怎样才能从中删除这些childNodes
?
回答by Harry
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.
您可以检查给定的子节点是否是文本节点或不使用nodeType
. 文本节点将具有nodeType
as 3
。我们可以使用数字或常量Node.TEXT_NODE
进行检查。
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>
回答by budamivardi
try to use jquery children method$("#test").children().size()
尝试使用 jquery children 方法$("#test").children().size()