tags:

views:

44

answers:

2

Given a child element, is there a simple means of determining how many parent tags separate it from a given 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;
}
+3  A: 
$element.parentsUntil( "selector" ).length
Evan Carroll
Excellent, thank you.
meagar
+3  A: 

See the .parentsUntil() method.

var seperatingTags = $(something).parentsUntil('div').size();
Matt