A Web Design Community curated by Chris Coyier

Code Snippets Gallery

Code Snippets > jQuery > Exclude $(this) from Selector Submit one!

Exclude $(this) from Selector

Let’s say you want to attach a click handler to every link on a page. The function for that click handler turns all the other links a different color.

var $allLinks = $("a");

$allLinks.click(function() {

     $allLinks.not(this).css("color", "red");

});

You can use the .not() function to remove elements from a set, so padding this to that function will remove the current element before the color change.

4 Responses

  1. Ant says:

    Better application for this:

    var allLinks = $("a");
    
    allLinks.click(function() {
    	allLinks
    		.removeClass('red')
    		.not(this)
    		.addClass('red');
    });

Leave a Comment

Remember:
  • Be nice.
  • Wrap multiline code in <pre> and <code> tags and escape it first (turn <'s into &lt;'s).
  • You may use regular HTML stuff like <a href="">, <em>, and <strong>
* This website may or may not contain any actual CSS or Tricks.