问题
I have a code with lots of submenus that share the same class name.
Here's a structure:
.menu
.sub-menu
.sub-menu
.sub-menu
.sub-menu
.sub-menu
.sub-menu
.elem
.elem
.sub-menu
Note that .sub-menu
may be infinite levels deep.
So how do I achieve this: when .elem
is clicked, I want to travers the DOM upwards until the top-most .sub-menu
is reached and apply a style to it. I am aware of .closest()
and .parent()
and .find()
, but I have no idea if jQuery has such feature such as .topMost(selector)
?
The only way I can think of is maybe running a loop and going through .closest('.sub-menu')
of the new element until its length is zero (there are no more parents with this class, so it must be the top-most). However, I think there should be a more practical approach to this.
回答1:
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.
回答2:
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.
回答3:
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;
}
来源:https://stackoverflow.com/questions/14787618/opposite-to-jquerys-closest-top-far-most