tony noriega tony noriega - 6 months ago 36
jQuery Question

Siblings of multiple list items

Ok, I have come to the conclusion that .siblings() by default only allows one selector or element to be the parent, and only the rest can be siblings.

How would one say to apply a class to multiple items and remove the class from the rest of the siblings?

$("#CarePointSAHAIDID").click(function() {
$("li.carepoint, li.saha, li.idid").addClass("active").siblings().removeClass("active");

Sorry, I thought I posted the HTML

<li class="hometownnorth"><a href="#"></a></li>
<li class="clearwater"><a href="#"></a></li>
<li class="kootenai"><a href="#"></a></li>
<li class="carepoint"><a href="#"></a></li>
<li class="saha"><a href="#"></a></li>
<li class="idid"><a href="#"></a></li>
<li class="hometowneast"><a href="#"></a></li>
<li class="portneuf"><a href="#"></a></li>
<li class="mountainview"><a href="#"></a></li>


You can just remove the collection by adding .not():

$("li.carepoint, li.saha, li.idid").addClass("active").siblings().not("li.carepoint, li.saha, li.idid").removeClass("active");

jsFiddle example

The docs for .siblings() actually says:

If you need an exclusive list of siblings, use $collection.siblings().not($collection).

A simple alternative is to remove the active class from all the list items first and then just add them to the ones you want:

$("li.carepoint, li.saha, li.idid").addClass("active");

jsFiddle example