简体   繁体   中英

How to toggle class to child only of current clicked class

I am trying to toggle a class for an element when a parent class is clicked, but since it's a menu where most classes are the same I don't want to toggle all children with that class, only the child of of the parent that is currently clicked.

My html structure:

<li>
    <a href="">Toepassingsgebied managementsysteem</a>
    <i class="mdi mdi-plus-box menuicon dropdown"></i>
    <ul class="dropdown-content menuliststyle">
        <li>Algemene bedrijfsgegevens</li>
        <li>Organogram</li>
        <li>Toepassingsgebied managementsysteem</li>
    </ul>
</li>

Then in my footer I got the following code:

$( document ).ready(function() {
    $(".menuicon").on("click", ".dropdown-content" function() {
       $(this).toggleClass("dropdown-show");
       console.log('test');
    });
});

So I want to fire the function when .menuicon is clicked but only toggle the class for its current child.

I also tried this:

$( document ).ready(function() {
    $(".menuicon > dropdown-content").on("click", function() {
       $(this).toggleClass("dropdown-show");
       console.log('test');
    });
});

But I am not even seeing test in my console, so what is the correct way to do this?

So I want to fire the function when .menuicon

In that case target the .menuicon class,. And looking at your HTML, you then want the next sibling,.. in jquery this is next ..

eg.

 $( document ).ready(function() { $("body").on("click", ".menuicon", function() { $(this).next().toggleClass("dropdown-show"); }); }); 
 .menuicon { color: red; cursor: pointer; } .dropdown-content { display: none; } .dropdown-content.dropdown-show { display: block; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <li> <a href="">Toepassingsgebied managementsysteem</a> <i class="mdi mdi-plus-box menuicon dropdown">▼</i> <ul class="dropdown-content menuliststyle"> <li>Algemene bedrijfsgegevens</li> <li>Organogram</li> <li>Toepassingsgebied managementsysteem</li> </ul> </li> <li> <a href="">Toepassingsgebied managementsysteem</a> <i class="mdi mdi-plus-box menuicon dropdown">▼</i> <ul class="dropdown-content menuliststyle"> <li>Algemene bedrijfsgegevens</li> <li>Organogram</li> <li>Toepassingsgebied managementsysteem</li> </ul> </li> 

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