You get 5 because there are two elements and three text nodes inside this line, childNodes
is exactly that: child nodes. There are several types of nodes (primarily: elements, text nodes, and comment nodes). Here are the nodes in this structure:
$(function(){ console.log("nodeType 1 is Element, 3 is Text"); var child = document.getElementById("row"); var i; for (i = 0; i < child.childNodes.length; ++i) { console.log(i + ": nodeType = " + child.childNodes[i].nodeType); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <table> <tr id="row"> <td> This is td </td> <td> This is td2 </td> </tr> </table> <div id="subpage"> </div>
If you want only children, use the DOM children
property (available for all modern browsers, but not for some very old ones)
$(function(){ console.log("nodeType 1 is Element, 3 is Text"); var child = document.getElementById("row"); var i; for (i = 0; i < child.children.length; ++i) { console.log(i + ": nodeType = " + child.children[i].nodeType); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <table> <tr id="row"> <td> This is td </td> <td> This is td2 </td> </tr> </table> <div id="subpage"> </div>
... or jQuery children
method :
$(function(){ console.log("nodeType 1 is Element, 3 is Text"); var child = document.getElementById("row"); var i; $(child).children().each(function(i) { console.log(i + ": nodeType = " + this.nodeType); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <table> <tr id="row"> <td> This is td </td> <td> This is td2 </td> </tr> </table> <div id="subpage"> </div>
source share