daGUY
daGUY

Reputation: 28743

jQuery: select all links other than this one

I have an unordered list with five list items, each with a link inside of 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 one of these links, I want to select all of the other ones and then do something to them (apply a class, etc.).

How do I do this?

Upvotes: 9

Views: 15802

Answers (3)

Control Freak
Control Freak

Reputation: 13233

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

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

Upvotes: 2

Guffa
Guffa

Reputation: 700322

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

});

Upvotes: 28

James M
James M

Reputation: 16718

Inside the click callback:

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

Upvotes: 10

Related Questions