Snippets Collections
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)
var tracker = {};
var depth = 0;
var prevNode;
Array.from(document.querySelectorAll("*")).forEach(node => {
    if (!tracker[node.tagName]) tracker[node.tagName] = 1;
    else tracker[node.tagName]++;
    console.log("Node depth:", node.tagName, depth);
    if (node.parentNode != prevNode) depth++;
    prevNode = node;
});
console.log(tracker);
star

Wed May 04 2022 12:56:13 GMT+0000 (UTC) https://stackoverflow.com/questions/33903929/iterate-through-html-dom-and-get-depth

#depth #recursive #tag #childnodes
star

Tue May 03 2022 15:17:05 GMT+0000 (UTC) https://stackoverflow.com/questions/33903929/iterate-through-html-dom-and-get-depth

#node #depth

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension