DOM 中孩子的深度 [英] depth of a child in the DOM
问题描述
我有什么办法可以知道基于容器的孩子的深度.示例:
<ul><li>1</li><li>2</li><li id="xelement">3</li><li>4</li><li>5</li>
您应该为xelement"获得 2(从 0 开始).知道礼"在同一水平.
谢谢
假设你想找到一个参照某个任意祖先的孩子的深度.
function depth(parent,后代){变量深度 = 0;var el = $(后代);var p = $(parent)[0];而 (el[0] != p) {深度++;el = el.parent();}返回深度;}//示例调用:深度(.mainContent",li")
一个完整的解决方案需要处理指定的父代不是后代的祖先的情况.
或者,仅当您支持 ES5 及更高版本时,直接使用 DOM 节点才能消除对 jQuery 的依赖:
function depth(parent,后代){无功深度= 0;而 (!descendant.isEqualNode(parent)) {深度++;后代 = 后代.parentElement;}返回深度;}//示例调用:深度(document.querySelector('.mainContent'),document.querySelector('li'))
Can I have any way to know which is the depth of a child based on a container. Example:
<div id="dontainer">
<ul>
<li>1</li>
<li>2</li>
<li id="xelement">3</li>
<li>4</li>
<li>5</li>
</ul>
</div>
You should get 2 for "xelement" (taking as starting at 0). Knowing that the "li" are at the same level.
Thanks
Assuming you want to find the depth of a child in reference to some arbitrary ancestor.
function depth(parent, descendant) {
var depth = 0;
var el = $(descendant);
var p = $(parent)[0];
while (el[0] != p) {
depth++;
el = el.parent();
}
return depth;
}
// Example call:
depth(".mainContent", "li")
A complete solution will need to handle the case where the specified parent isn't an ancestor of descendant.
Alternatively, and only if you support ES5 and above, working directly with DOM nodes can eliminate the dependency on jQuery:
function depth(parent, descendant) {
var depth = 0;
while (!descendant.isEqualNode(parent)) {
depth++;
descendant = descendant.parentElement;
}
return depth;
}
// Example call:
depth(document.querySelector('.mainContent'), document.querySelector('li'))
这篇关于DOM 中孩子的深度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!