Тома Томов Тома Томов - 19 days ago 8
HTML Question

JavaScript DOM traverse

I am trying to get all childs from

<article class="birds">
, but cant reach these ones that are in
<li class="bird">Hawk
... I am trying to do it with recursion.

function traverse (node){
node = document.getElementsByClassName(node)[0];
for(let i=0; i<node.childNodes.length; i++){
let child = node.childNodes[i];
if(child.nodeName == '#text'){
continue;
}else{
console.log(child.nodeName.toLowerCase() +
": class=\"" + child.className +"\"");
if(child.nodeType === document.ELEMENT_NODE){
traverse(child.className);
}
}

}
}
traverse('birds');

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<header>
<h1>Living Creatures</h1>
</header>
<section>
<article class="birds">
<h2 class="birds-heading">Birds</h2>
<ul class="birds-list">
<li class="bird">Nightingale</li>
<li class="bird">Owl</li>
<li class="bird">Hawk
<ul>
<li class="sub-bird">Black Hawk</li>
<li class="sub-bird">Chicago Hawk</li>
</ul>
</li>
<li id="eagle" class="bird">Eagle</li>
<li class="bird">Sparrow</li>
<li class="bird">Falcon</li>
<li class="bird">Blackbird</li>
</ul>
</article>
<article class="mammals">
<h2 class="mammal-heading">Mammals</h2>
<ol class="mammal-list">
<li id="dolphin" class="mammal">Dolphin</li>
<li class="mammal">Elephant</li>
<li class="mammal">Hyena</li>
</ol>
</article>

</section>
<script type="text/javascript" src="testing.js"></script>>
</body>
</html>


Is it because
<ul>
element does not have a class attr? The ouput i get is :

h2: class="birds-heading"
ul: class="birds-list"
li: class="bird"

Answer

You cannot get to the li with class birds-list since the parent ul does not have a class and your traverse code is dependant on a class.

Instead, you can tweak the code to traverse by node. I have made the change to your code and it works.

function traverse (node){
    for(let i=0; i<node.childNodes.length; i++){
        let child = node.childNodes[i];
        if(child.nodeName == '#text'){
            continue;
        }else{
            console.log(child.nodeName.toLowerCase() + 
                        ": class=\"" + child.className +"\"");
            if(child.nodeType === document.ELEMENT_NODE){
                traverse(child);
            }
        }

    }
}
traverse(document.getElementsByClassName('birds')[0]);
Comments