Given a child element, is there a simple means of determining how many parent tags separate it from a 开发者_如何学JAVAgiven selector? Something like .closest(selector)
which returns the number of parent()
calls required to reach any element selected by the the given selector.
An (untested) implementation of what I'm looking for:
$.fn.distance = function(selector) {
var $parent = $(selector); // TODO check that element exists
var $current = $(this);
var depth = 0;
while ($current != $parent) {
$current = $current.parent();
++depth;
}
return depth;
}
$element.parentsUntil( "selector" ).length
See the .parentsUntil()
method.
var seperatingTags = $(something).parentsUntil('div').size();
精彩评论