javascript - Iterate through HTML DOM and get depth - Stack Overflow

PHOTO EMBED

Wed May 04 2022 12:56:13 GMT+0000 (Coordinated Universal Time)

Saved by @luckymage #depth #recursive #tag #childnodes

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)
content_copyCOPY

tree,recursive

https://stackoverflow.com/questions/33903929/iterate-through-html-dom-and-get-depth