I'm having a problem traversing the DOM tree. Here's my code:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="main.js"></script>
<title>DOM Traversing</title>
</head>
<body>
<ol>
<li>
<a href="">One</a>
<ul>
<li><a href="">1.1</a></li>
<li><a href="">1.2</a></li>
<li><a href="">1.3</a></li>
</ul>
</li>
<li><a href="">Two</a></li>
<li><a href="">Three</a></li>
<li><a href="">Four</a></li>
</ol>
</body>
</html>
Javascript:
var rootNodeChildren = document.childNodes;
var rootNodeChild;
for (var i = 0; i < rootNodeChildren.length; ++i) {
rootNodeChild = rootNodeChildren[i];
console.log(rootNodeChild);
console.log(rootNodeChild.childNodes.length);
for (var j = 0; j < rootNodeChild.childNodes.length; ++j) {
console.log(rootNodeChild.childNodes[j]);
}
}
This this the result of the following code:
The document object has 2 children
- DOCTYPE html
- html tag
The html tag should have 2 children as well.
- head tag
- body tag
But the output shows that html tag has only one child i.e. head tag
Can someone please explain why that is?
In the example, the HTML is not relevant but I intend to write a recursive function to traverse all elements of DOM tree.
rootNodeChild.childNodes[i].tagName
rather than the object. Also, usechildren
instead ofchildNodes
, so you skip the text nodes.