How to remove a class from one set of siblings without affecting other elements with same class

873 Views Asked by At

I have the following:

<div class="attributes_set_1>
   <label class="attributes"><input type="radio" value="1" /></label>
   <label class="attributes"><input type="radio" value="2" /></label>
   <label class="attributes"><input type="radio" value="3" /></label>
</div>

<div class="attributes_set_2>
   <label class="attributes"><input type="radio" value="1" /></label>
   <label class="attributes"><input type="radio" value="2" /></label>
   <label class="attributes"><input type="radio" value="3" /></label>
</div>

I'm trying to add an active class to any of the first set of radio buttons when clicked but also remove the class if selecting a different one from the same set. The problem is that I need to be able to select from the next set of radio buttons without removing the active class from any other set.

I've tried several selectors but I think the way to make it work would be by selecting the children of that specific parent class.

How can I select only the siblings of a particular parent class in order to remove the active class?

$('.attributes').children().removeClass('active');

How can I add the active class to whatever other radio I clicked whether it is part of the same siblings or not once I make the removeClass() work?

$(this).addClass('active');

Thanks to anyone for the help.

2

There are 2 best solutions below

0
On

Assuming this is the radio button to which you have added the active class then you can find the siblings of the parent label elements and then remove the class from its input elements

$(this).parent().siblings().find('input').removeClass('active');
0
On

Try this:

$('.attributes input').click(function() {
    $(this).addClass('active').parent().siblings('.attributes').find('input').removeClass('active');
})