Duck Duck - 7 months ago 9
HTML Question

Selecting an element within a parent element of another

I want to find out how, I am able to select an element which is outside the element which has been clicked.

<li class="nav-item dropdown">
<a href="javascript;" class="menu-toggle">
<i class="fa fa-server"></i>
<span>Server</span>
</a>
<ul class="dropdown-menu">
<li>
<a>
<i class="fa fa-home"></i>
<span>Item one</span>
</a>
</li>
</ul>
</li>


Within the code, I want to make it so when the user clicked the button, which will trigger the link, it will then display the "dropdown-menu", by adding the class "open" to list-item "nav-item dropdown".

I have more than one dropdown menu within the navigation too, so I cannot just simple select "dropdown-menu" and then make it visible, as it will make all of the dropdown menu's visible. So is there any way of doing this? I have tried to select the element, but it just selects them all, and I just cannot get my head around it.

Much appreciated.

Answer

You can use $(this).next() DEMO

$('.menu-toggle').click(function(e) {
  e.preventDefault();
  $(this).next('.dropdown-menu').toggleClass('open');
})