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.
Assuming by 'opposite of closest' you want the 'furthest' parent element, you can use parents().last()
, like this:
$('.elem').on('click', e => {
var $topSubMenu = $(e.target).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.
If instead you mean that you want the 'closest' child element, then you can use find('.submenu').first()
, like this:
$('.elem').on('click', e => {
var $topSubMenu = $(e.target).find('.submenu').first();
});
You could potentially use children('.submenu')
here instead of find()
- it depends how many levels down the DOM tree you need to traverse.