简体   繁体   中英

Select an element by a class that multiple elements share with jQuery

I want to select an element with the class 'submenu-expand', and add another class to it.

$('.menu-item').on('click',function(){
$('.submenu-expand').toggleClass('expanded')
})

This code works, but the problem is that multiple elements share that class, so jQuery selects all of them. I tried to do it this way since '.submenu-expand'is inside of 'menu-item':

$('.menu-item').on('click',function(){
$('this>.submenu-expand').toggleClass('expanded')
})

HTML:

<li id="menu-item-940" class="menu-item">
<a href="" >אודות</a>
<button class="submenu-expand" tabindex="-1"></button>
</li>

What is the correct way to do that?

You mean

 $('.menu-item').on('click', '.submenu-expand', function() { $(this).toggleClass('expanded') })
 .expanded { border: 1px solid black; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li id="menu-item-940" class="menu-item"> <a href="">אודות</a> <button class="submenu-expand" tabindex="-1">Click</button> </li> <li id="menu-item-940" class="menu-item"> <a href="">אודות</a> <button class="submenu-expand" tabindex="-1">Click</button> </li> <li id="menu-item-940" class="menu-item"> <a href="">אודות</a> <button class="submenu-expand" tabindex="-1">Click</button> </li> <li id="menu-item-940" class="menu-item"> <a href="">אודות</a> <button class="submenu-expand" tabindex="-1">Click</button> </li> </ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM