I have a menu with submenu with a structure like this:
<ul>
<li>
<a class="navigation-item">Menu Item 1</a>
<a class="submenu-toggle" />
<ul class="submenu">
<li>
<a class="navigation-item">Submenu Item 1</a>
</li>
</ul>
</li>
</ul>
I want to add a class to submenu-toggle if Submenu Item 1 is selected. How can I find the submenu-toggle in this case?
closest('li')
won’ work, this will only find the li after the submenu. closest('li > .submenu-toggle')
doesn’t work either because the .submenu-toggle
has to be an ancestor of the submenu item. If I could select the correct li, I could then use find('.submenu-toggle')
. But how do I select the correct li?
5
Answers
To achieve this, you can traverse the DOM to find the correct
li
element that contains both thesubmenu-toggle
and the selected submenu item.
It is way better to find the root of the context, i.e., the container and do the actions relative to that. In the snippet below I loop the
li
children of#myul
as the roots of the contexts, create aclick
handler on the.navigation-item
which willtoggle
theactive
class ofsubmenu-toggle
.You need to traverse the DOM structure from the selected submenu item up to the parent
<li>
thaat contains both the submenu and the toggle button. Then, you can find the.submenu-toggle
within that parent<li>
.I don’t know how it translates to jquery, but in plain Javascript you can just do:
Regardless of the already above commented approach of mine …
… there is a big chance that the OP does not need any JavaScript based solution at all in order to style the toggle-element. This of cause does not imply that JS is entirely obsolete in order to achieve all of the required menu-behaviors, but I would give even that one a real good try.