jQuery Custom Selector Execution Exploration

Posted January 15, 2010 at 9:06 PM by Ben Nadel

Tags: Javascript / DHTML

The other day, on my blog post about creating custom jQuery selectors, Scott Smith mentioned to me that he was having some performance issues with a custom selector. Specifically, he mentioned that in some experimentation, he noticed that his custom selector was being run against more nodes than he expected. Until then, I had never really thought deeply about how a custom jQuery selector was actually executed, so I figured I'd do some experimentation of my own.

In the following code, I have a Span element wrapped in a series of nested Div elements. Two of the outer-most Div elements have the class, "parent":

  • <div class="parent">
  • <div class="parent">
  • <div>
  • <span>Here is some inner text.</span>
  • </div>
  • </div>
  • </div>

When I run the code (below), I'm going to locate the Span element; then, I'm going to call the parents() method on it, using the following selector:

div.foo:testSelctor.bar

Notice that we are running 4 tests on each node returned by parents():

  • Test for the Div tag.
  • Test for the class, ".foo".
  • Test for the custom jQuery selector, ":testSelector".
  • Test for the class, ".bar".

The custom jQuery selector, ":testSelector," simply logs its invocation arguments to the console such that we can see where in the process it is being called.

Now that you have an idea of what I'm planning to do, let's take a look at the actual code:

  • <!DOCTYPE HTML>
  • <html>
  • <head>
  • <title>jQuery Custom Selector Execution Exploration</title>
  • <style type="text/css">
  •  
  • div {
  • border: 1px solid #CCCCCC ;
  • padding: 10px 10px 10px 10px ;
  • }
  •  
  • div.parent {
  • border-color: gold ;
  • }
  •  
  • </style>
  • <script type="text/javascript" src="jquery-1.4.js"></script>
  • <script type="text/javascript">
  •  
  • // This simply outputs the arguments passed to the
  • // selector for debugging purposes.
  • jQuery.expr[ ":" ].testSelector = function(
  • node,
  • index,
  • properties,
  • collection
  • ){
  • // Output the custom selector arguments.
  • console.log( node, index, collection );
  • return( true );
  • };
  •  
  •  
  • // When the DOM is ready, initialize.
  • jQuery(function( $ ){
  •  
  • // Get all of the spans.
  • var spans = $( "span" );
  •  
  • // Get all the parent divs with the class "parent".
  • //
  • // NOTE: This selector is using a custom selector
  • // sandwiched bewteen two CLASS selectors.
  • var parents = spans.parents(
  • "div" +
  • ".foo" +
  • ":testSelector" +
  • ".bar"
  • );
  •  
  • // Add a red, thick border.
  • parents.css( "border", "2px solid red" );
  •  
  • // Output the parents.
  • console.log( ".... parents ...." );
  • console.log( parents );
  • });
  •  
  • </script>
  • </head>
  • <body>
  •  
  • <h1>
  • jQuery Custom Selector Execution Exploration
  • </h1>
  •  
  • <div class="parent">
  • <div class="parent">
  • <div>
  • <span>Here is some inner text.</span>
  • </div>
  • </div>
  • </div>
  •  
  • </body>
  • </html>

As you can see, the ":testSelector" custom jQuery selector simply outputs the node being examined, its index, and the collection from which it came. When we run this code, here is what FireBug is telling me:

 
 
 
 
 
 
jQuery Custom Selector Execution Exploration - Some Cases Do Not Use Progressing Trimming Of The Node Collection. 
 
 
 

This is very interesting! Look at the nodes in the collection being examined by the custom selector:

  • div
  • div.parent
  • div.parent
  • body
  • html

This completely changes the way I thought selectors were executed. I understand that Sizzle runs tree traversal in reverse; however, as my tests are all on the same node, I figured that would not matter. Of course, this has nothing to do with forward vs. reverse selecting - this has to do with progressive collection trimming. It appears that each selector execution does not perform any progressive collection trimming; meaning, neither the "div" selector, nor the ".foo" selector, nor the ".bar" selector had any pre-trimming affect on the node collection before it was passed into the testSelector custom jQuery selector method.

This is fascinating! As far as ".foo", ".bar", and ":testSelector" go, I figured I might not be able to count on order; but, I was almost certain that the "Div" tag selector would have done at least some pre-trimming of the collection. After all, I thought Sizzle used the getElementsByTagName() method.

Of course, it's not quite that straightforward! This exploration used the parents() method; if I were to replace the above use of parents() with any of the following direct jQuery selections:

  • $( "div.foo:testSelector.bar" );
  • $( "div.foo:testSelector" );
  • $( ".foo:testSelector" );

... then, the ":testSelector" method would never get executed. As it turns out, when you do direct selections, jQuery does perform progressive trimming of the target node collection. I assume it does this using variations of getElementsByTagName(), getElementsByClassName(), and whatever new query methods browsers now support, before the node collection is passed off to (or rather, not off to) ":testSelector."

Ultimately, it doesn't really matter how the node collections get trimmed, since undesired nodes will be removed one way or another based on your selector; but, it's something that I have never thought deeply about before, and it's interesting to see how selector behavior changes (behind the scenes) based on the context of the selection.




Reader Comments

Jan 19, 2010 at 1:08 PM // reply »
14 Comments

Ben:

We do a weekly showcase of any new, interesting stuff to show our group. This week I will be doing a modified presentation of the information in this post (as well as turning some folks on to your site :) This is great stuff and really important when you are going for performant code. Thanks for delving into this topic (:


Jan 19, 2010 at 2:00 PM // reply »
11,238 Comments

@Kristopher,

My pleasure. jQuery is really fascinating stuff and I'm constantly discovering more ways to use it. I hope your presentation goes well.


Jan 21, 2010 at 3:35 AM // reply »
2 Comments

Hi Ben,
How to get the jQuerify button in FireBug?


Jan 22, 2010 at 9:44 PM // reply »
11,238 Comments

@Ngoc,

I am not sure what you mean? I don't know what "jQuerify button" is.


Jan 28, 2010 at 10:39 AM // reply »
2 Comments

@Ben,
In the above screenshot (http://www.bennadel.com/resources/uploads/jquery_custom_selector_execution.gif), in FireBug, there's a button "jQuerify" beside button Clear and Profile, how to get it?
Thank you.


Jan 28, 2010 at 10:41 AM // reply »
11,238 Comments

@Ngoc,

Hmm, funky. I never noticed that before. I am not even sure what it does.


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 17, 2013 at 7:42 PM
HashKeyCopier - An AngularJS Utility Class For Merging Cached And Live Data
Ben - thanks so much for posting these Angular articles and findings, they've been a huge help towards learning one of the more 'complex' JavaScript frameworks out there (IMO). I have been using Angu ... read »
May 16, 2013 at 5:01 PM
UPDATE: Parsing CSV Data Files In ColdFusion With csvToArray()
Your code was the closest thing I've found to obtaining some direction for converting ISO fields to values that CF can translate properly. Thank you for posting! ... read »
May 15, 2013 at 10:37 PM
Very Simple Pusher And ColdFusion Powered Chat
hi id making plz easy ... read »
May 15, 2013 at 6:07 PM
Making SOAP Web Service Requests With ColdFusion And CFHTTP
Ben, you once again saved my bacon at work. Thank you, thank you, thank you! ... read »
May 15, 2013 at 4:15 PM
What If All User Interface (UI) Data Came In Reports?
@Josh, Thanks! @Ben, I definitely recommend the David West book "Object Thinking" I've been quoting from. It goes deeply into the philosophy and history of OO programming. His breadth ... read »
May 15, 2013 at 11:36 AM
Ask Ben: Print Part Of A Web Page With jQuery
I found this helpfull when you need to keep (refresh) the original parent page after closing the iframe child print dialog (Hoping you're not using a form at this time so it won't submit again): On ... read »
May 14, 2013 at 7:13 PM
What If All User Interface (UI) Data Came In Reports?
@Jonah, If there's any books you'd recommend on the subject of domain modelling, I'd love to hear it. I just downloaded the free PDF of "Domain Driven Design Quickly". Figured I'd give it ... read »
May 14, 2013 at 6:57 PM
The UX Of Prototyping: Low-Fidelity Is The New High-Fidelity
@Phillip, I'm not sure I follow what you mean? Are you saying that you looked at the list of widgets provided by the jQuery UI and let that be your style guide? ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools