Link...">

JQuery: select all links except this one.

I have an unordered list with five list items, each with a link inside it:

  <ul>
     <li> <a href="#"> Link 1 </a> </li>
     <li> <a href="#"> Link 2 </a> </li>
     <li> <a href="#"> Link 3 </a> </li>
     <li> <a href="#"> Link 4 </a> </li>
     <li> <a href="#"> Link 5 </a> </li>
 </ul>

Using jQuery, whenever I click on any of these links, I want to select all the others and then do something with them (apply the class, etc.).

How to do it?

+7
source share
3 answers

Use the not method to remove an element from a jQuery object:

 $(function(){ $('ul li a').click(function(){ $('ul li a').not(this).addClass('other'); }); }); 
+22
source

Inside the click callback:

 var others = $(this).closest('ul').find('a').not(this); 
+10
source

You can select all the links and then use .not(this) to accomplish what you want, for example:

  $("a").click( function(){ $("a").not(this).css("color","red"); }); 
+2
source

All Articles