Opposite to jQuery's .Closest (Top/Far-Most?)
The question is slightly misleading as .closest
() could be misinterpreted. Actually it means search up the tree until the first match is found. So the opposite is search down the tree until a match is found and that method is .first().
To find all descendants one might use find()
. The opposite of find()
is parents()
.
closest() (all levels) For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
first() (all levels) Reduce the set of matched elements to the first in the set
parents() (all levels) Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.
parent() (next level only) Get the parent of each element in the current set of matched elements, optionally filtered by a selector.
find() (all levels) Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
Assuming by 'opposite of closest' you want the 'furthest' parent element, you can use parents().last()
, like this:
$('.elem').click(function() {
var $topSubMenu = $(this).parents('.sub-menu').last();
});
Note, you want the last element in the array as jQuery traverses up the DOM, so the top-level item will the final one in the collection.
Here's a JavaScript-only solution, based on the polyfill for closest()
.
function furthest(s) {
var el = this.parentElement || this.parentNode;
var anc = null;
while (el !== null && el.nodeType === 1) {
if (el.matches(s)) anc = el;
el = el.parentElement || el.parentNode;
}
return anc;
}