Skip to main content
Ben Nadel at Scotch On The Rocks (SOTR) 2011 (Edinburgh) with: Guust Nieuwenhuis
Ben Nadel at Scotch On The Rocks (SOTR) 2011 (Edinburgh) with: Guust Nieuwenhuis ( @Lagaffe )

Step Debugging jQuery Selectors

By on

NOTE: This blog post was inspired by a post that Ray Camden did a while back about an AIR-based jQuery selector tester.

I was talking to some people a while back about debugging jQuery selectors. To me, the hardest part about debugging jQuery selectors is that when they are not returning the set of nodes you want, or nodes at all, its hard to tell where you went wrong. As such, I thought it would be really cool to build a little jQuery selector test harness that would step through the jQuery selector search path, one step at a time, highlighting each intermediary set of nodes in the process. This way, you can see where in the path you went wrong.

As you can see, the final nodes that would be returned by your target jQuery selector are highlighted in Gold. If your jQuery selector doesn't match any nodes, all you will see are shades of gray.

Since this blog post isn't so much about the code, but rather the overall functionality, I'll just display the code below without going in depth into what it does. I wrote the code in haste and am not going to stand by its "cleanliness".

The HTML Page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
	<title>Untitled</title>
	<script src="jquery-1.3.2.js" type="text/javascript"></script>
	<script src="trace.js" type="text/javascript"></script>
	<script type="text/javascript">

		$(
			function(){
				var jForm = $( "#tester" );
				var jText = jForm.find( ":text" );
				var jButton = jForm.find( ":button" );
				var objTester = new SelectorTester( 1000 );

				// Hook up form submit.
				jForm.submit(
					function(){
						// Run test.
						objTester.Test( jText.val() );

						// Kill form submission.
						return( false );
					}
					);
				}
			);

	</script>
</head>
<body>

	<form id="tester">
		<p>
			<input type="text" size="40" />
			<input type="submit" value="Run Test" />
		</p>
	</form>


	<h1>
		jQuery Selector Testing
	</h1>

	<p>
		This is the jQuery selector tester. The way it works is
		that you enter your selector in the above form and hit
		<strong>"Run Test"</strong>. The tester then parses your
		selector into its sub-parts and runs each sub-part
		individually.
	</p>

	<p>
		The beauty of this is that it highlights each intermediary
		node collection and then <em>pauses</em> before moving
		onto the next intermediary collection. This gives you the
		ability to trace the route of the selector.
	</p>

	<div>

		<p>
			I am in a <span>DIV > P</span>
		</p>

		<p>
			I am in a DIV > P
		</p>

	</div>

</body>
</html>

The Javascript code behind:

// I am the base class for the testing.
function SelectorTester( intPause ){
	this.OriginalSelector = "";
	this.Pause = (intPause || 1000);
	this.Selectors = [];
	this.Timeout = null;
}


// I clean the selectore before parsing.
SelectorTester.prototype.CleanSelector = function( strSelector ){
	// Trim selector.
	strSelector = $.trim( strSelector );

	// Make sure we only ever have single spaces.
	strSelector = strSelector.replace(
		new RegExp( " +", "g" ),
		" "
		);

	// Hook up the child selector with next selector.
	strSelector = strSelector.replace(
		new RegExp( "> +", "g" ),
		">"
		);

	// Return cleaned selector.
	return( strSelector );
}


// I parse the selector into selectors classes.
SelectorTester.prototype.ParseSelector = function( strSelector ){
	var arrSelectors = [];

	// Clean and break the selector into sub-selectors.
	var arrSubSelectors = this.GetSubSelectors(
		this.CleanSelector( strSelector )
		);

	// For each sub-selector, we want to create a selector.
	$.each(
		arrSubSelectors,
		function( intI, strSelector ){
			arrSelectors.push(
				new Selector( strSelector )
				);
		}
		);

	// Return the collection of selectors.
	return( arrSelectors );
}


// I break up the original selector into sub-selectors.
SelectorTester.prototype.GetSubSelectors = function( strSelector ){
	var arrSubSelectors = this.OriginalSelector.match(
		new RegExp(
			"[^\\[,]+(\\[[^\\]]+\\][^\\[,]*)*",
			"gi"
			)
		);

	// Loop over each to trim.
	return(
		$.map(
			arrSubSelectors,
			function( strSelector, intI ){
				return( $.trim( strSelector ) );
			}
			)
		);
}


// I reset the selector tester.
SelectorTester.prototype.Reset = function(){
	// Clear any existing testing timeout.
	clearTimeout( this.Timeout )

	// Clear the original selector.
	this.OriginalSelector = "";

	// Destroy each selector.
	$.each(
		this.Selectors,
		function( intI, objSelector ){
			objSelector.Destroy();
		}
		);

	// Clear selectors.
	this.Selectors = [];
}


// I run the tests.
SelectorTester.prototype.Test = function( strSelector ){
	var objSelf = this;

	// Reset any existing test.
	this.Reset();

	// Store the selector and parse it.
	this.OriginalSelector = this.CleanSelector( strSelector );
	this.Selectors = this.ParseSelector( this.OriginalSelector );


	// Define a method that will test each intermediary
	// collection of nodes.
	function PerformTest(){
		var blnKeepTesting = false;

		// Loop over each tester.
		for (var i = 0 ; i < objSelf.Selectors.length ; i++){

			blnKeepTesting = (
				objSelf.Selectors[ i ].ShowNextSelector() ||
				blnKeepTesting
				);

		}

		// Check to see if we should perform another test.
		if (blnKeepTesting){

			// Launch test again shortly.
			objSelf.Timeout = setTimeout(
				PerformTest,
				objSelf.Pause
				);

		}
	}

	// Start test harness.
	PerformTest();
}


// -------------------------------------------------------- //
// -------------------------------------------------------- //


// I am a class for individual testing.
function Selector( strSelector ){
	this.OriginalSelector = strSelector;
	this.Parts = this.ParseSelector( strSelector );
	this.Colors = [ "#F0F0F0", "#D0D0D0", "#B0B0B0", "#909090", "#707070", "#505050" ];
	this.Depth = 0;
	this.Nodes = $( "body" );
	this.ResetNodes = $( [] );
}


// I parse the selectir into parts.
Selector.prototype.ParseSelector = function( strSelector ){
	return(
		strSelector.match(
			new RegExp(
				"[^\\s\\[]+(\\[[^\\]]+\\][^\\s\\[]*)*",
				"gi"
				)
			)
		);
}


// I show the next selector.
Selector.prototype.ShowNextSelector = function(){
	if (this.Depth >= this.Parts.length){
		return( false );
	}

	// Get the next set of nodes and colorize them.
	this.Nodes = this.Nodes
		.find( this.Parts[ this.Depth ] )
		.css( "background-color", this.Colors[ this.Depth ] )
	;

	// Build up the reset nodes collection.
	this.ResetNodes = this.ResetNodes.add( this.Nodes );

	// Increase the depth.
	this.Depth++;

	// Check to see if we have any more nodes to search.
	// If not, we want to highlight this ndoe in gold
	// to signify its a final node.
	if (this.Depth >= this.Parts.length){
		this.Nodes.css( "background-color", "gold" )
	}

	// Return true/false for next selectors.
	return( this.Depth < this.Parts.length );
}


// I reset the select (take away background coloring).
Selector.prototype.Destroy = function(){
	// Clear node colors.
	this.ResetNodes.css( "background-color", "transparent" );
}

Want to use code from this post? Check out the license.

Reader Comments

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!
Ben Nadel