In jQuery you can call closest
to find the closest parent.
If I have a a
in a li
in a ul
in a td
in
Use .parents(). It returns a list of all parents that are ordered from closest to farthest.
The difference between using this and using .closest(selector)
is that it accepts a jQuery object instead of a selector string, which has to be hard coded. Meanwhile jQuery objects can be collections and so can be generated on the fly.
(function($) {
$.fn.getClosest = function(testElements) {
var element = $(this);
var parents = element.parents();
var indexClosest = Number.MAX_VALUE;
testElements.each(function() {
var index = parents.index($(this));
if (index > -1 && index < indexClosest)
indexClosest = index;
});
return parents.eq(indexClosest);
};
})(jQuery);
Use the function like this:
$("a").getClosest($("table, ul"))
Fiddle with advanced use case