我試圖從<article class="birds">
獲得所有孩子,但無法到達這些在<li class="bird">Hawk
中的孩子......我試圖用遞歸來實現。JavaScript DOM遍歷
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>
是不是因爲<ul>
元素沒有class attr?在輸出中我得到的是:
h2: class="birds-heading"
ul: class="birds-list"
li: class="bird"
非常感謝! –