javascript检查子节点是否为元素或文本节点

时间:2014-07-26 12:48:04

标签: javascript node.js

我对childNodes的问题如下:

 <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

似乎每个\ntextnode都被视为child,如何从childNodes删除这些内容?

2 个答案:

答案 0 :(得分:22)

您可以使用nodeType检查给定子节点是否为文本节点。文本节点的nodeType3。我们可以使用数字或the constant Node.TEXT_NODE进行检查。

&#13;
&#13;
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);
  }
}
&#13;
<ol>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Coca Cola</li>
</ol>
&#13;
&#13;
&#13;

答案 1 :(得分:-3)

尝试使用jquery children方法
$("#test").children().size()

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