如何获取关于Element的DOM节点深度


How to get DOM node depth with respect to Element?

如何获取DOM节点相对于HTML元素的深度?(这是作为子级的HTML标记,而不是文本节点)。

例如:

<div> // root node
  here is my text node // but it wont be considered in level increment
   <p> // level 1
      <label>  // level 2
             here is another text node
      </label>
   </p>
</div>

这应该返回2。

我试过这个,但它不起作用:

function getDepth($node, $depth) {
foreach ($node->childNodes as $child):
    if($child->nodeType === 1):
        $depth++;
    endif;
    if ($node->childNodes):
        getDepth($child, $depth);
    endif;
endforeach;
return $depth;
}

沿着树向上走。像这样的事情应该做(未经测试):

function getDepth($node)
{
    $depth = -1;
    // Increase depth until we reach the root (root has depth 0)
    while ($node != null)
    {
        $depth++;
        // Move to parent node
        $node = $node->parentNode;
    }
    return $depth;
}

我推荐这个:

function findNodeLevel($node) { // $node is a DOMNode 
    $xpath = explode('/', $node->getNodePath());
    return count($xpath);
}