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

Dzhuneyt picture Dzhuneyt · Feb 9, 2013 · Viewed 17.3k times · Source

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.

Answer

jenson-button-event picture jenson-button-event · Jun 13, 2013

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.