Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

dom - Opposite to jQuery's .Closest (Top/Far-Most?)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...