Enrique Sampaio Enrique Sampaio - 7 months ago 13
Javascript Question

Priority when more than one element use the same class

I'm having a problem with jQuery.

I'm doing a mobile menu using jQuery with sub menus. I need to use the same class to activate all the menus because they will be created dynamically, but when I do this, when I click on a item, all the others show their sub-item too.

To be clear, here's an example:

<ul>
<li class="OpenMenu"><a href="javascript:void(0);">Menu 1</a>
<ul class="sub-item">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</li>
<li class="OpenMenu"><a href="javascript:void(0);">Menu 2</a>
<ul class="sub-item">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</li>
<li class="OpenMenu"><a href="javascript:void(0);">Menu 3</a>
<ul class="sub-item">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</li>
</ul>


I need each menu to show its sub-items only when is clicked, but all using the same class. I'm doing the "open" effect of the menus with jQuery.

Answer

You can achieve by below code, find() method will drill down to only its child items and find sub items

$(".OpenMenu").click(function(){
$(this).find('.sub-item').show();

});

DEMO (covers only displaying required sub menu)

To view how to hide other sub items and display only current items, use this http://jsfiddle.net/Lboyrqnc/2/