jQuery: select all links other than this one

14,805

Solution 1

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

});

Solution 2

Inside the click callback:

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

Solution 3

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");
 });
Share:
14,805
daGUY
Author by

daGUY

Front-end web developer with 10 years of professional experience. Highly knowledgable of various web technologies, frameworks, and tools (HTML5, CSS/SCSS, JavaScript/jQuery, JSON, Zurb Foundation, Git, etc.). Multiple years of experience working in an Agile environment with Atlassian utilities (JIRA, Confluence, Stash, Bitbucket, etc.). Work experience ranges from tiny startups (employee #7!) to large international businesses (Mercedes-Benz, Nestlé), where I've written front-end code for a wide variety of projects including music streaming apps, corporate websites, and mobile-responsive landing pages and email campaigns.

Updated on July 21, 2022

Comments

  • daGUY
    daGUY almost 2 years

    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?