如果我有一个html dom,如下所示,没有使用任何库(如jQuery),我如何迭代任何给定元素的所有子元素。我需要检查是否在这些元素上设置了一些自定义属性。
<div id="testme">
<span><a></a></span>
<div>
<ul>
<li><a></a></li>
</ul>
</div>
</div>
答案 0 :(得分:4)
让我的答案变得简单,以便了解问题。尝试其中任何一种,你想要吗?
//direct descendent nodes
var children = document.getElementById('id').childNodes;
// or
//all nodes below the top node?
var children = document.getElementById('id').getElementsByTagName('*');
答案 1 :(得分:3)
使用html dom + javascript非常简单。
var printhere = document.getElementById("printhere");
function stepthrough(el, prefix){
prefix = prefix || "";
if(el ){
//Ignore the text nodes
if(!el.nodeName || !(/#text/i.test(el.nodeName))){
printhere.innerHTML += "<br />" + prefix + el.tagName;
if(el.firstChild){
stepthrough(el.firstChild, prefix + "--");
}
}
if(el.nextSibling){
stepthrough(el.nextSibling, prefix)
}
}
}
stepthrough(document.getElementById("testme"));
您可以自定义代码的printhere.innerHTML += "<br />" + prefix + el.tagName;
部分以适应任何内容。
您可以在此fiddle找到一个有效的例子。
这是一个递归函数,遍历给定节点的所有子节点和子节点