Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

node.js - javascript check if child node is element or text node

i have problem with childNodes as below :

 <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 or textnode is considered a child ,how can i remove these from childNodes?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...