jqueryfindjquery-selectorshtml-listsclosest

open closest ul on click jQuery


when clicking a.market-metro, open closest ul.children.

<ul class="drop-padding">
<li>
    <a class="market-metro">text</a>
    <ul class="children">...</ul>
</li>
<li>
    <a class="market-metro">text</a>
    <ul class="children">...</ul>
</li>
<li>
    <a class="market-metro">text</a>
    <ul class="children">...</ul>
</li>

I have the following but not working:

jQuery(".market-metro").click(function(){
    if (jQuery(".market-metro").closest('li').find('ul.children').hasClass("expanded")) {
        jQuery(".market-metro").closest('li').find('ul.children').removeClass("expanded").slideUp(250);
    } else {
        jQuery(".market-metro").closest('li').find('ul.children').addClass("expanded").slideDown(250);
    }
});

Solution

  • you need to use $(this) .. and you can use .next() instead of closest and find and use .not()

    $(".market-metro").click(function(){
        $('ul.children').not( $(this).next('ul.children')).removeClass("expanded").slideUp();
        $(this).next('ul.children').toggleClass("expanded").slideToggle(250);
    });
    

    Working Demo

    Note: be sure to include jquery