开发者

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

开发者 https://www.devze.com 2023-01-18 06:46 出处:网络
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 pare

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

精彩评论

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