javascript JS/jQuery:获取元素的深度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4710943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JS/jQuery: Get depth of element?
提问by mpen
What's the easiest way to get the depth of an element in pure JavaScript or jQuery? By "depth" I mean how many elements deep is it nested, or how many ancestors does it have.
在纯 JavaScript 或 jQuery 中获取元素深度的最简单方法是什么?“深度”是指它嵌套了多少个元素,或者它有多少个祖先。
回答by polarblau
How about:
怎么样:
$('#my-element').parents().length
回答by Fostah
An additional note. If you want to get the depth relative to a certain context you can do:
补充说明。如果您想获得相对于特定上下文的深度,您可以执行以下操作:
var depth = $("#my-element","#ContextContainerID").parents("ul").length;
Above, I'm searching for how many UL's are within the container #ContextContainerID
上面,我正在搜索容器中的 UL 数量 #ContextContainerID
回答by amosrivera
Supposing you don't want to include body and html tag in the parents to count use:
假设您不想在父项中包含 body 和 html 标签来计算使用:
$("#element").parents("*").not("body,html").size()
Online demo here: http://jsfiddle.net/zaJff/
在线演示在这里:http: //jsfiddle.net/zaJff/
回答by shybovycha
Try something like this:
尝试这样的事情:
<html>
<head>
<title>MooExample</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("li").click(function() {
alert($(this).parents().length);
});
});
</script>
</head>
<body>
<ul>
<li>moo</li>
<li>foo</li>
<li>fasoo</li>
<li>moasf</li>
<li>moosadg</li>
<li>moo1</li>
<li>moo412</li>
<li>moo613a</li>
</ul>
</body>
</html>
回答by Jon z
My advice would be to rethink the way you are solving your problem - I think finding the number of generations between nodes probably isn't the best way to go, it sounds like a solution that will be likely to break easily by future changes to the code.
我的建议是重新考虑您解决问题的方式 - 我认为找到节点之间的代数可能不是最好的方法,这听起来像是一个解决方案,很可能会因未来对代码。
If you insist however, the solution (by Cletus, in native javascript) seems pretty good on this page: find number of nodes between two elements with jquery?
然而,如果你坚持,这个页面上的解决方案(由 Cletus 提供,在原生 javascript 中)似乎非常好: 使用 jquery 查找两个元素之间的节点数?
回答by ADJenks
function elementDepth(el){
var depth = 0
while(null!==el.parentElement){
el = el.parentElement
depth++
}
return depth
}
console.log(elementDepth(document.getElementById('test')))
<div>
<span id="test">Hi</span>
</div>
It says 3 in this example because it counts the outer <div>, the <body>and the <html>tag.
在这个例子中它说 3 是因为它计算了外部的<div>、<body>和<html>标签。

