如何获得关于HTML元素的DOM节点的深度? (即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;
}
答案 0 :(得分:2)
向上走树。这样的事情应该做(未经测试):
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;
}
答案 1 :(得分:0)
我推荐这个:
function findNodeLevel($node) { // $node is a DOMNode
$xpath = explode('/', $node->getNodePath());
return count($xpath);
}