Home > other >  jQuery how to target children of siblings?
jQuery how to target children of siblings?

Time:11-12

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');
    });
});

CodePudding user response:

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.

CodePudding user response:

<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

  • Related