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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:40:30  来源:igfitidea点击:

javascript check if child node is element or text node

javascriptnode.js

提问by talkhabi

i have problem with childNodesas 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 \nor textnodeis 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 nodeTypeas 3. We can either use the number or the constant Node.TEXT_NODEfor checking.

您可以检查给定的子节点是否是文本节点或不使用nodeType. 文本节点将具有nodeTypeas 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()

http://jsfiddle.net/72Ya3/2/

http://jsfiddle.net/72Ya3/2/