Skip to content

Instantly share code, notes, and snippets.

@Alex1990
Last active February 17, 2016 08:42
Show Gist options
  • Select an option

  • Save Alex1990/d5fb84c368486cc8bee0 to your computer and use it in GitHub Desktop.

Select an option

Save Alex1990/d5fb84c368486cc8bee0 to your computer and use it in GitHub Desktop.
An jQuery function to get the closest descendant element which matches the specified selector.
/**
* closestDescendant
* An jQuery function to get the closest descendant element which matches the specified selector.
* The search strategy is breadth-first.
*/
;(function () {
$.fn.closestDescendant = function (selector) {
var $elem = $();
this.each(function () {
var matchedSet = $(this).find(selector).toArray();
var queue = $(this).children().toArray();
while (queue.length) {
var $current = $(queue.shift());
if ($.inArray($current[0], matchedSet) > -1) {
$elem = $elem.add($current);
break;
}
queue = queue.concat($current.children().toArray());
}
});
return $elem;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment