Help me Help me - 2 months ago 12
CSS Question

Jquery only targeting clicked classes parent not others?

I want to my menu element to display a submenu when I click on child button. But I also have identical html and classes on other menu elements. So when I press a button it opens all submenus and closes the open ones.

I want it to work so that when I click a button, only his parents submenu opens and closes if clicked.

<ul>
<li class="menu-item current-menu-item">
<a href="">Menu1</a>
<button>click</button>
<ul class="submenu">
<li>asdasd</li>
</ul>
</li>
<li class="menu-item">
<a href="">Menu2</a>
<button>click</button>
<ul class="submenu">
<li>asdasd</li>
</ul>
</li>
<li class="menu-item">
<a href="">Menu3</a>
<button>click</button>
<ul class="submenu">
<li>asdasd</li>
</ul>
</li>
</ul>

.submenu {
display: none;
}
.current-menu-item .submenu {
display: block;
}

$(".menu-item button").click(function(){
$(".menu-item button").parent('.menu-item').toggleClass("current-menu-item");
});


http://codepen.io/rKaiser/pen/QKgQVQ

Thank you.

Answer
$(".menu-item button").click(function(){
  $(this).parent('.menu-item').toggleClass("current-menu-item");
});

otherwise the jQuery selector finds all elements with the class .menu-item button

Comments