jQuery selector Property

Why didnt i notice this a long time ago? It’s been there since 1.3.

This property contains a string representing the matched set of elements

In code this translates to:

$( '#foo .bar a' ).click( function(){
	console.log( $( this ).selector );
	// logs '#foo .bar a'

This can be very useful whenever you wanna keep the context of the DOM isolated. A common use case is when using delegate() and live() methods, where you need to listen for events on the elements being parsed in, but the DOM may change over time:

foo : function( $bar) { 
	//So this will not work 
	$bar.live( 'mouseover mouseout' , function( e ){}); 

	//And .selector to the rescue 
	$( $bar.selector ).live( 'mouseover mouseout' , function( e ){}); 

	//Example using using delegate 
	$( document ).delegate( $bar.selector , 'mouseover mouseout' ,  function( e ){ 
		if ( e.type === 'mouseover' ) { 
			doMouseOverStuff( $( this ) ); 

Performance wise you’re skipping the referenced collection of jQuery elements and querying the Sizzle selector engine once again – so dont use it unless you have to. Also a well structured low-coupled application can account for many of these issues.

But giving the right circumstances I’ll still defend its use.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>