Grow your CSS skills. Land your dream job.

Last updated on:

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.

Comments

  1. Ant

    Better application for this:

    var allLinks = $("a");
    	
    allLinks.click(function() {
    	allLinks
    		.removeClass('red')
    		.not(this)
    		.addClass('red');
    });
  2. Tem Corner
    Permalink to comment#

    Since having a lot of links on a page with this script means that jQuery will manipulate each of the elements and do stuff in the class-attributte, this can become quite expensive and slow.

    A better way would be to use a common wrapper class.
    That way jQuery only touches the current link and the previously clicked ones. Way faster and cheaper on larger pages and good practice in general.

    The body-class part is not mandatory, the links could be made red by default leaving only two css rules. and two lines of javascript within the click function.

    jQuery(function(){
    
    	// Only do the body class once
    	var bodyIsClassed = false;
    	
    	// Instead of binding handlers to all anchor-tags, watch live()
    	$( 'a' ).live( 'click', function(e){
    		e.preventDefault();
    
    		$( '.clicked' ).removeClass( 'clicked' );
    		$( this ).addClass('clicked');
    		if ( !bodyIsClassed ) {
    			$( 'body' ).addClass( 'highlight-anchors' );
    		}
    	});
    });

    See also http://krinkle-tools.grizzdesign.nl/other-anchors.html

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like ```this```. You don't need to escape code in backticks, Markdown does that for you.

Sadly, it's kind of broken. WordPress only accepts a subset of HTML in comments, which makes sense, because certainly some HTML can't be allowed, like <script> tags. But this stripping happens before the comment is processed by Markdown (via Jetpack). It seems to me that would be reversed, because after Markdown processes code in backticks, it's escaped, thus safe. If you think you can fix this issue, get in touch!

If you need to make sure the code (typically HTML) you post absolutely posts correctly, escape it and put it within <pre><code> tags.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".