Assuming you want to find the depth of the child in relation to an 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;
}
depth(".mainContent", "li")
The complete solution will have to handle the case where the specified parent is not the ancestor of the descendant.
Alternatively, and only if you support ES5 and higher, working with DOM nodes directly can eliminate jQuery dependency:
function depth(parent, descendant) {
var depth = 0;
while (!descendant.isEqualNode(parent)) {
depth++;
descendant = descendant.parentElement;
}
return depth;
}
depth(document.querySelector('.mainContent'), document.querySelector('li'))
source
share