开发者

How can I determine how deeply nested a child element is within a parent?

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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜