Iterate through HTML DOM and get depth
Note that the other answers are/where not realy correct ...
This will also filter out "TEXT" Nodes, and not output the BODY tag.
function getDef(element, def) {
var str = ""
var childs = element.childNodes
for (var i = 0; i < childs.length; ++i) {
if (childs[i].nodeType != 3) {
str += childs[i].nodeName + " " + def + "<br />"
str += getDef(childs[i], def + 1)
}
}
return str
}
// Example
document.body.innerHTML = getDef(document.body, 0)
<div>
<img src="foo.jpg">
<p>
<span>bar</span>
</p>
</div>
Write a recursive function which tracks the depth:
function element_list(el,depth) {
console.log(el+' '+depth);
for(var i=0; i<el.children.length; i++) {
element_list(el.children[i],depth+1);
}
}
element_list(document,0);
As CodeiSir points out, this will also list text nodes, but we can filter them out by testing the nodeType
. Variations on this code will allow/ignore other node types as desired.
function element_list(el,depth) {
if (el.nodeType === 3) return;