0

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');
    });
});
3
  • You need to properly close the li and a tags first.
    – Gerard
    Nov 11, 2021 at 14:30
  • @Gerard FYI you don't need to close li (yes to a) : MDN li The end tag can be omitted if the list item is immediately followed by another <li> element, or if there is no more content in its parent element.
    – freedomn-m
    Nov 11, 2021 at 14:38
  • Note that .bind() was deprecated ages ago in favor of .on()
    – j08691
    Nov 11, 2021 at 17:50

2 Answers 2

2

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.

0
<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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.