简体   繁体   中英

jQuery how to target children of siblings?

I'm having issues removing the active class in a certain div. I use two filters, but somehow if I click on one, the other filter also gets the active class removed. How can I only target and remove the active class of the children of siblings?

Here's my HTML:

<ul class="filter">
<li class="option"> <a class="link active">
<li class="option"> <a class="link">
<li class="option"> <a class="link">
</ul>

<ul class="filter2">
<li class="option"> <a class="link active">
<li class="option"> <a class="link">
<li class="option"> <a class="link">
</ul>

And here's my jQuery code:

$(document).ready(function () {
    $('.link').bind('click', function() {
        // remove the active class from all elements with active class
        $('.active').removeClass('active')
        // add active class to clicked element
        $(this).addClass('active');
    });
});

You can use $(this).closest("ul") to find th ul containing the element that was clicked, then find to find the .active elements in just that ul :

$('.link').on('click', function() {
    const $this = $(this);
    $this.closest("ul").find(".active").removeClass("active");
    $this.addClass('active');
});

Side note: I changed bind to on . bind has been deprecated for years.

<div>
    <ul class="filter">
        <li class="option"> <a href="javascript:;" class="link active">1</a></li>
        <li class="option"> <a href="javascript:;" class="link">2</a></li>
        <li class="option"> <a href="javascript:;" class="link">3</a></li>
    </ul>
    <ul class="filter">
        <li class="option"> <a href="javascript:;" class="link active">4</a></li>
        <li class="option"> <a href="javascript:;" class="link">5</a></li>
        <li class="option"> <a href="javascript:;" class="link">6</a></li>
    </ul>
</div>
<script>
    $(function() {
        $('.filter .link').click(function(){
            $(this).addClass('active').closest('.filter').find('.link').not(this).removeClass('active');
        });
    });
</script>

check this one-liner

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