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.