If I have a html dom as shown below, with out using any library (like jQuery) how can I iterate through all the sub elements of any given element. I need to check whether some custom attributes are set on those elements.
<div id="testme">
<span><a></a></span>
<div>
<ul>
<li><a></a></li>
</ul>
</div>
</div>
If I have a html dom as shown below, with out using any library (like jQuery) how can I iterate through all the sub elements of any given element. I need to check whether some custom attributes are set on those elements.
<div id="testme">
<span><a></a></span>
<div>
<ul>
<li><a></a></li>
</ul>
</div>
</div>
Share
Improve this question
edited Jan 6, 2011 at 3:32
jcolebrand
16k12 gold badges77 silver badges122 bronze badges
asked Jan 6, 2011 at 3:21
Arun P JohnyArun P Johny
388k68 gold badges531 silver badges532 bronze badges
2 Answers
Reset to default 4Keeping my answer simple for the benefit of getting to the meat of the matter. Try either of these, which would you like?
//direct descendent nodes
var children = document.getElementById('id').childNodes;
// or
//all nodes below the top node?
var children = document.getElementById('id').getElementsByTagName('*');
It is pretty easy using the 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"));
You can customize the printhere.innerHTML += "<br />" + prefix + el.tagName;
part of the code to fit it into any anything.
You can find a working example in this fiddle.
This is an recursive function which goes through all the children and subchildren of the given node
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744211782a4563367.html
评论列表(0条)