Example DOM Tree
Image via Wikipedia

jQuery does a wonderful job of traversing the DOM tree, so you might ask why you would like to do this yourself?
I recently encountered a requirement to count the maximum ‘depth’ of a DOM tree. I.e. find the level of the deepest nested element. So, I managed to knock this up in a few minutes:

function Recurse($item, depth) {
    $item.each(function() {
        depth.count++;
        if (depth.count > depth.max) {
            depth.max = depth.count;
        }
        Recurse($(this).children(), depth);
    });
    depth.count--;
    return depth.max;
}

$(document).ready(function() {
    alert(Recurse($("body"), { count: 0, max:0 }));
}

A few points to note about this

  • depth is an object with two members, count and max. We want to keep a count of the current and maximum depth, but want to avoid global variables (it’s better practice, and makes the solution more self-contained).
  • JavaScript doesn’t allow us to pass variables by reference. Using the variables within the passed depth object means we can pass values to lower levels of recursion.
  • We must pass an object in our first call. Technically the function can be improved by including a check for this.
  • The function returns depth.max. Although the return value doesn’t matter when the function is called recursively, its useful for passing our intended value out to the original calling function.

You can test this out on JsFiddle: http://jsfiddle.net/RqHzf/

Enhanced by Zemanta
,

Have you ever found yourself wanting to test out a bit of HTML/CSS/JavaScript without having access to an IDE or being bothered to fire it up?

Do you want to hack prototype a bit of code quickly without fuss?

Or maybe you’re one of those StackOverflow answerers that Race To Get The First Answer In.

If your answer is ‘yes’ or ‘I am actually’ then there’s probably a myriad of different resources you can call upon to help out, but you might consider JSFiddle

I created  a really simple bit of code:

HTML

<input type="checkbox" />

JavaScript/jQuery

$("input").click(function(){alert("test");});

Then I selected ‘jQuery 1.4.2.’ from the ‘Choose Framework’ section and clicked run.

When I clicked on the checkbox, everything hung together like a dream:

At the time of writing the blurb stated that it was still under heavy development, however I still thought it was a genuinely nice little tool that I wanted to share.

Enhanced by Zemanta
, , , ,

Last year I held a jQuery course, and was fortunate enough to recieve very generous praise from my peers, including the following:

What parts of the training did you feel were of most value?Biscuits
The overview of the key paragdim interjected with real examples expedited learning

What parts of the training did you feel were of least value?
The lack of biscuits

What, if anything, would you change about the course?
Provide biscuits

Any further comments?
More biscuits please

So there we have it. Biscuits, cakes, muffins, coffees and teas. Bribing your audience can always help!

, ,

Back in September 2008 Microsoft announced that it would be shipping jQuery with Visual Studio going forward. This was pretty momentous news at the time, as noted in the jQuery Blog.

True to its word, Microsoft Shipped jQuery with Visual Studio 2010, and it is now included by default in your ASP.NET web projects.

Further to this, Microsoft is now actively contributing to the jQuery project itself.

All this really underlines the emerging dominance of jQuery and gives extra reason for this to be JavaScript library of choice for anyone thinking of adopting a JavaScript framework.

,

Synopsys

Use chaining as an alternative to variable caching and multiple selector calls.

Where chaining is used, appropriate line breaks and indentation should be used.

Do not over-chain. For long chains it acceptable to cache intermediate objects in a variable.

Description

Chaining is one of the signature features of jQuery. Used correctly, it can reduce the amount of code we have to write and the amount of data that is held in memory.

Chaining can be considered as an alternative to:

  • Caching jQuery objects in local variables
  • Performing multiple selections

Where chaining is used, appropriate line breaks and indentation should be used.

When to Use Chains

Chains should not compromise the readability of the code. For long chains, finding and defining a formatting and indentation strategy can be troublesome.

It can be better in these instances to cache your jQuery object in a separate variable.

When a JavaScript object is cached in jQuery, the reference to the object is actually stored. This occupies a minimal amount of memory, leaving negligible performance degradation.

The items show some indentation strategies, and a representation with a cached variable:

Chain Formatting Examples

Long Chains – Indentation Strategy 1

$("#MyTable").append(
    objButton.parents("tr").clone()
        .find(".RowTitle")
            .text("Row " + String(AddCount)).end()
        .find(".MySelect1")
            .attr("id", "SomeId" + String(AddCount))
                .change(function() { ChangeFundRow() }).end()
        .find(".MySelect2")
            .attr("id", "SomeOtherId" + String(AddCount)).end()
);

Long Chains – Indentation Strategy 2

$("#FundTable").append(
    objButton
        .parents("tr")
            .clone()
                .find(".RowTitle")
            .text("Row " + String(AddCount))
            .end()
                .find(".MySelect1")
                .attr("id", "SomeId" + String(AddCount))
                .change(function() {
                    ChangeFundRow();
                })
            .end()
                .find(".MySelect2")
                .attr("id", "SomeOtherId" + String(AddCount))
            .end()
);

To the untrained eye, either of the above may take some deciphering. In this case, a better strategy could be to cache your selections in a separate variable:

Long Chains – Caching Variable

var $clonedRow = objButton.parents("tr").clone();
$clonedRow.find(".RowTitle")
          .text("Row " + nAddCount); 

$clonedRow.find(".MySelect1")
    .attr("id", "FundManager" + nAddCount)
    .change( ChangeFundRow ); 

$clonedRow.find(".MySelect2")
          .attr("id", "FundName" + nAddCount); 

$clonedRow.appendTo("#FundTable");

jQuery Coding Standards Menu

  1. jQuery Variables
  2. DOM Manipulation
  3. Events
  4. Page Style and Layout Changes
  5. Effects and Animation
  6. Selectors
  7. Plugins
  8. Chaining
, ,

Synopsis

Do not reinvent the wheel. Use plugins if they fit your functional requirement.

Ensure the plugins are fit-for-purpos, well regarded and well tested.

Description

Plugins are a way by which any developer can extend the jQuery library. They are often useful, frequently well tested and supported, and may well cut down on development time.

The following are some commonly used plugins:

Reviewing Plugins for Use

The review process for including a plugin should encompass some sort of investigation into the plugin itself. The following aspects should be examined:

  • The current level of use I.e. is it widely adopted? Those with a large number of users will be well tested and developed.
  • For which version of jQuery was it written? Is it still valid for your current version of jQuery?
  • The current level of support. E.g. does it have a website with examples, etc. An example of one with good support is BlockUI (http://malsup.com/jquery/block/#)
  • Quality of plugin comments – A quick scan of the code will see if it’s well documented. If its well documented, then it should be well written.
  • How well is it regarded?. A quick internet search across the jQuery community and its users should reveal this.
  • Availability of vsdoc js for intellisense. Not critical, but would be a factor in choosing two plugins that were identical to each other in every other aspect.

Writing Plugins

Whenever you find yourself developing some jQuery that could be considered generic, and could certainly adopted within other areas of the code base, then you should consider turning it into the jQuery plugin.

The ‘how’ of doing this is outside the scope of these standards. Refer to jQuery literature (department books and online) for how to do this. Experienced jQuery developers may also be able to assist.

As a starting point, any plugin should begin with the following closure code convention:

    function($){
        //plugin code
    }(jQuery);

jQuery Coding Standards Menu

  1. jQuery Variables
  2. DOM Manipulation
  3. Events
  4. Page Style and Layout Changes
  5. Effects and Animation
  6. Selectors
  7. Plugins
  8. Chaining
, ,

Synopsis

Use #ID selector wherever possible. It is the fastest.

Ensure slower selectors are optimised for performance – Combine them with faster selectors where possible.

Custom selectors must be kept simple, as they may end up being run upon every element in the DOM.

Avoid needless selector combinations.

Description

Selectors are ranked by performance as follows:

  1. #Id
  2. Element
  3. .class, :pseudoclass and :custom

The Class and PseudoClass and Custom selectors are slower than ID and Element selectors. The deficiency of their performance can be mitigated by combining them with other selector types, so do this wherever possible.

Examples

    $(".oddRows");                   //Inefficient: scans DOM for all elements with oddrows class
    $("tr.oddRows");                 //More efficient: Searches only <tr>s with oddrows class
    $("#MyTable tr.oddRows");        //More efficient: searches descendents of #MyTable
    $("#MyTable>tbody>tr.oddRows");  //Best: searches immediate children

In these examples, we have combined CSS style selectors to obtain better performance in two ways:

  • Element.WithClass – I.e. search for element with the specified class name
  • #Id Descendents – I.e. search within descendents of the Id.
  • #Id>Children – I.e. search only immediate children

The optimisation of selector performance is essential for efficient jQuery. This must be a major consideration for developers and code-reviewers alike.

Custom Selectors

It is possible within jQuery to define custom selectors, as per the following example:

    $.extend($.expr[":"], {
        textboxEmpty: function(el) {
            return $(el).val() === "";  //must return boolean
        }
});
alert($(":text:textboxEmpty").length);

Custom selectors must be kept simple, as they may end up being run upon every element in the DOM.

Be aware that Custom and Pseudoclass selectors are, at best, as slow as class selectors (complex custom selectors may be even be slower!). Therefore you should attempt to optimise their performance by utilising some of the techniques described above.

For a tutorial on writing custom selectors, check out my blog post here.

Pitfalls and Traps

Assuming Children and Descendants

The example “#MyTable>tbody>tr.oddRows” helps us demonstrates the potential pitfalls of assuming specific children/descendants. Had we written this as “#MyTable>tr.oddRows” then our selector would have returned nothing!

Correct Use of Parent-Child

The selector $(“#MyTable .oddRows”) will return all elements in the DOM with the oddrows class assigned (there is a space between #MyTable and .oddRows)

However, the selector $(“#MyTable.oddRows”) will probably return nothing, as the code imples that we are looking for the table with the Id #MyTable that has the class oddrows assigned to it.

Given the naming convention in the example it seems unlikely that that the table will have the class assigned.

Needless Selector Combinations

The Id of an element should be unique. Therefore there is no need to combine it with other selectors. For example, the selector $(“#MyTable.TableClass”) is probably pointless as the query for #MyTable will already have returned at most one element.

In the same vein, the selector $(“div #MyTable”) is also pointless. Here we are going to select all divs in the DOM, and then scan that subsection for #MyTable.

Defining an Id at the start of a Parent-Child selector can, however improve selector performance greatly, and is strongly encouraged. See selector performance examples above.

jQuery Coding Standards Menu

  1. jQuery Variables
  2. DOM Manipulation
  3. Events
  4. Page Style and Layout Changes
  5. Effects and Animation
  6. Selectors
  7. Plugins
  8. Chaining
, ,

Synopsis

Adopt a restrained and consistent approach to implementing animation functionality.

Description

jQuery provides some basic functionality, the simplest of which is demonstrated by the following code:
    $("#MyDiv").hide("slow");

Here, the hiding of MyDiv is animated.

It is important that a consistent approach to the use of effects and anuimation is adopted across the web application.

There is a temptation when discovering this functionality to ‘go nuts’ and have divs whizzing in from all angles with buttons flashing and all hell breaking loose. In general you should try to show restraint when using animation.

If possible, feed animation use into UI standards.

jQuery Coding Standards Menu

  1. jQuery Variables
  2. DOM Manipulation
  3. Events
  4. Page Style and Layout Changes
  5. Effects and Animation
  6. Selectors
  7. Plugins
  8. Chaining
, ,

Synopsis

Avoid making changes to individual CSS styles using the jQuery API functions.

Use CSS Classes intead.

Description

Avoid using direct CSS style changes (using .css() ), and inbuilt style functions .length(), .width(), etc.

Instead, declare the styles in a class within a CSS StyleSheet file (not inline within an HTML file!), and use .addClass(), .removeClass() or .toggleClass() upon your selecteded object(s).

For example, avoid this type of declaration:

    $("#MyTR").css({
       "background-color":"gray"
    });

Use instead:

    $("#MyTR").addClass("HighlightRow");

    /*In CSS File:*/
    .HighlightRow
    {
       background-color:gray;
    }

This promotes correct separation of content and style.

Embedding style changes in JavaScript/jQuery has the following implications when it comes to rebranding or changing a site’s theme:

  • It is less likely that a consistent approach has been adopted with regard to styling making the task harder.
  • A bigger and more complex  impact analysis required to identify files that require changed.
  • More files require changed.
  • More files = more testing. As we will be changing JavaScript code, we will have to retest more than we otherwise would have.

A discussion on the merits of Behavioral Separation is outside the scope of this article. It may seem a little draconian to advise against using .css() and other style-change functions, but is essential when attempting to achieve this goal.

jQuery Coding Standards Menu

  1. jQuery Variables
  2. DOM Manipulation
  3. Events
  4. Page Style and Layout Changes
  5. Effects and Animation
  6. Selectors
  7. Plugins
  8. Chaining
, ,

Synopsis

1. Adopt a consistent approach when writing document ready events.

2. Use a document ready event in place of window onload.

3. No JavaScript or behavioural markup is to be included in HTML files.

4. Events must be late-bound within the $(document).ready()handler code itself.

5. Use the shorthand event syntax.

6. Anonymous function handlers must be limited to one line of code.

Document Ready Declaration

1. The handler for the document ready event must be an anonymous declared in the following form:

    $(document).ready(function(){
    	//all initialization
    });

This is clear, readable, and should be used ahead of other possible invocations of this functionality, which include:

    $(handler);
    $().ready(handler); //not recommended
    $(document).bind("ready", handler); //not fired if bound after document ready fires

(And, of course, ‘$’ is interchangeable with ‘jQuery’)

This standard stipulates the use of the given format, however the important aspect of this is the recommendation to adopt a consistent approach to writing document ready events.

2. A Document Ready handler must be specified in place of the window.onload event, except in the rare event where this is too soon: http://blog.arc90.com/2008/05/16/a-jquery-tip-dont-use-jquery/

Note: There is no limit on the number of document ready handlers that can be associated with a page. Event handlers are added to a stack that will be executed when the document is ready.

Binding and Behavioural Markup


3. No JavaScript or behavioural markup is to be included in HTML files. For example, the red-highlighted code should not be present in HTML any more:

    <input type="button" id="MyButton" onclick="OnClickMyButton()">

4. Events must be late-bound within the $(document).ready()handler code itself. For example:

    $(document).ready(function(){
        $("#MyButton").click(MyFunc);
    });

    function MyFunc(event){
    }

5. Use the shorthand event syntax:

    $("#MyButton").click(MyFunc); //use this
    $("#MyButton").bind("click", MyFunc); //instead of this

Event Handlers and Anonymous Functions
6. jQuery allows developers to specify anonymous functions for event handlers. For example:

    $("#MyButton").click(function(){//code});

However, to avoid On Ready Bloating (a side effect of late-binding where the document.ready() function handler becomes large, cumbersome, and unmaintainable), these anonymous function handlers must be limited to one line of code:

    $("#MyButton").click(function(){
        MyFunction();
    });

If we need to refer to the this object, we wrap it in a jQuery object, and pass it within our anonymous function (it is better practice to wrap in a jQuery object early on):

    $("#MyButton").click(function(){
        MyFunction($(this));
    });

jQuery will automatically pass the event object when calling our anonymous function. We can access it as follows:

    $("#MyButton").click(function(event){
        MyFunction($(this), event);
    });

Incidentally, the declaration for MyFunction for the above example would be:

    function MyFunction($this, event){
        //code
    }

As well as avoiding OnReady Bloating, this approach makes our code easier to debug and more readable.

jQuery Coding Standards Menu

  1. jQuery Variables
  2. DOM Manipulation
  3. Events
  4. Page Style and Layout Changes
  5. Effects and Animation
  6. Selectors
  7. Plugins
  8. Chaining
, ,

Synopsis

Manipulation of the Document Object Model (DOM) can be costly and inefficient, regardless of whether it is undertaken through jQuery or JavaScript.

The API provided by jQuery facilitates greater DOM manipulation, possibility outwith of the awareness of the developer.

Therefore, you should limit the amount of code that performs DOM Manipulation tasks.

Description

The challenge here is to recognise:

  1. When DOM Manipulation is being undertaken
  2. When it is being done in excess.

Both of these are open to interpretation as it is difficult to stipulate exactly what constitutes excessive DOM manipulation.

In general, very little DOM manipulation should really be undertaken. You should be hitting the DOM in this way only when is absolutely necessary.

Let us examine the following example:

    var $myList = $("#myList");   

    for (i=0; i<1000; i++){
        $myList.append("This is list item " + i);
    }

This code adds 1000 lines to an HTML list. This is done with 1000 successive calls to the .append() method, and hence, 1000 manipulations to the DOM.

The following code, modified from the example above demonstrates how this can be made more efficient:

    var $myList = $("#myList");
    var li = "";   

    for (i=0; i<1000; i++){
        li += "<li>This is list item " + i + "</li>";
    }  

    $myList.append(li);

In this example, the HTML is constructed in advance. The HTML is appended in one call, greatly reducing the amount of manipulation you undertake.

jQuery Coding Standards Menu

  1. jQuery Variables
  2. DOM Manipulation
  3. Events
  4. Page Style and Layout Changes
  5. Effects and Animation
  6. Selectors
  7. Plugins
  8. Chaining
, ,

Synopsys

All variables that are use to store/cache jQuery objects should have a name prefixed with a ‘$’.

Consider using chains in place of jQuery object variables.

Description

There is often a requirement to store/cache a jQuery selection in a holding variable. Where this is the case, you should prefix the variable name with a ‘$’.

For example:

    var $MyTable = $("#MyTable");
    $MyTable.addClass("MyTable");
    $MyTable.append("<tr></tr>");

Also, in conjunction with $(this):

    var $this = $(this);

Storing in a holding variable helps reduce the number of calls into jQuery, and enhances performance. The dollar notation on all jQuery-related variables helps us easily distinguish jQuery variables from standard JavaScript variables at a glance (e.g. string, integer, etc).

Cached Variables vs Chains

The above example could have been written efficiently as a chain like so:

    $("#MyTable").addClass("MyTable").append("<tr></tr>");

This has the advantage in removing the need for a cached variable, and in this particular case makes sense.

When chains become long, complex and especially hard to read, you should split them up, storing intermediate selections in a holding variable: http://stackoverflow.com/questions/1286829/is-there-a-preferred-way-of-formatting-jquery-chains-to-make-them-more-readable

This does not result in much (if any) of a performance hit. Objects are held as references, not values, so their impact is minimal: http://stackoverflow.com/questions/1287106/can-it-be-disadvantageous-to-store-jquery-objects-in-a-variable

The Chaining Standards cover this in more detail.

jQuery Coding Standards Menu

  1. jQuery Variables
  2. DOM Manipulation
  3. Events
  4. Page Style and Layout Changes
  5. Effects and Animation
  6. Selectors
  7. Plugins
  8. Chaining
, ,

Yes, maybe, and yet, a few days ago I code reviewed a bit of code like this:

     $("select[id='MySelect']").val(1);

Where, of course, an ID selector would have sufficed, and would have been faster, smaller and better:

     $("#MySelect").val(1);

jQuery isn’t a silver bullet against bad code. You can still write some quite horrific jQuery, and moreover, as JavaScript isn’t subject to precompilation you can ship syntactically incorrect jQuery.

If this were not enough, jQuery, and in particular the Sizzle Selector Engine does a lot ‘under the hood’ with regard to DOM manipulation and traversal. The consequence of this is that, although you code may look great, and be perfectly bug free, it may grind to a painful halt under real-world stupid-user scrutiny.

Standards can help guard against all of this. I’m not really wanting to get tried up in a discussion on the virtues of standards, but, in general, if you believe in them elsewhere, then they are equally valid here.

jQuery Coding Standards Menu

  1. jQuery Variables
  2. DOM Manipulation
  3. Events
  4. Page Style and Layout Changes
  5. Effects and Animation
  6. Selectors
  7. Plugins
  8. Chaining
, ,

Overview

The jQuery JavaScript library has established itself as the most dominant and widely-used JavaScript library available.

And yet, for me, there no sites that appear to pull together best practices for jQuery development in a way that Douglas Crockford has done with his JavaScript Code Conventions.

So, while researching the language for the rollout of a jQuery course, I found myself needing to develop a set of standards.

Some time on from this, lessons have been learned and I feel I have a good workable set of jQuery standards. I have decided to present these in a series of posts that fall under the following headers:

  1. jQuery Variables
  2. DOM Manipulation
  3. Events
  4. Page Style and Layout Changes
  5. Effects and Animation
  6. Selectors
  7. Plugins
  8. Chaining

Scope

The initial scope of these posts is intended to cover coding from the core jQuery library. only. It is not intended to cover the use of jQuery UI, or other high-profile plugins.

Such is the significance and widespread adoption of some of these add-ons, for example the  jQuery forms validator, or anything that malsup has written,  that a set of good practice guidelines for these may also be of benefit. But not here, not now at least.

Audience

These standards were developed following the rollout of jQuery within a corporate development community.

They were a result of capturing developer experiences, and evolved over a number of iterations to suit the ecosystem of a very specific development community.

I do believe, however, that they have a broad relevance and use, and will serve any jQuery developer well.

jQuery Version

These standards were developed against jQuery 1.4.2.

I Don’t Think jQuery Should / Needs To be constrained

I disagree, which is why I’ve written these standards. I’ve felt this warrants a separate article.

I think you/a standard/everything here is wrong

And you may be correct.

I’m happy to change, debate and listen to any opinions to this end, but I would encourage you to bear in mind the audience, and motivation for this. The standards were developed for use within a corporate programming environment, and although I’ve always tried to carry these into my everyday programming adventures, I realise they are not for everyone.

For me, standards are there to make you think about what you are doing. On occasions I think standards can be broken, but these scenarios will be exceptions, not rules. And if you are thinking about deviating from a standards, so you should be thinking about commenting. For a well disciplined programmer, good standards lead to better code and better comments.

You may also feel that I’ve missed something. Quite possibly – this was evolved over a number of months in response the practices adopted by a specific development community. I hope for these standards to evolve now they have been exposed to the outside world!

, ,

For me, one of the best, yet under-utilised features of jQuery is the custom selector.

Custom selectors are another way to extend jQuery for your own means, and to hive off worker functionality that needn’t clutter your code.

This article was written for jQuery version 1.4.2

The Old Way

To demonstrate this, I’m going to use a simple example for identifying elements with empty value attributes. Consider the scenario where you want a bit of client-side script to alert you if there are any empty textboxes upon form submission:

    var i = 0;
    $("input:text").each(function() {
        if ($(this).val() === "") {
            i++;
        }
    });

    if (i > 0) {
        alert("Not all fields filled out");
    }

Now, at face-value then this is a quite valid way of doing things. However, for me, this is a worker task – a task that in theory can be hived away elsewhere so as not to clutter your code. We can of course, make it into a function:

    function HasEmpty(selector)
        var i = 0;
        $("input:text").each(function() {
            if ($(this).val() === "") {
                i++;
            }
        });
        return (i > 0);
    }

But this really isn’t all that flexible. Do you want to return the count of items? Or just a Boolean indicating if any are empty? And it’s not really all that jQuery-like. The New Way So, how can we make this a little more elegant? By using custom selectors, of course. In fact, we will just be reusing a language feature of jQuery that jQuery itself uses. Have you ever wondered how jQuery implements the CSS Pseudo-Class Selectors such as :first-child or :hidden, etc? Well, under the hood, these are all really just custom selectors built into the jQuery framework. This goes for all of the 30+ Pseudo-Class selectors in jQuery. To do this, we make use of the little known property jQuery.expr[':'] in conjunction with jQuery.extend like so:

    $.extend($.expr[":"], {selectorName:[anonymous function]});

The interesting part of this is [anonymous function]. This function will be called for every element against which this selector runs (much in the same way that .each works). If the function returns true” then the current element will be included in the result set. Conversely, a return value of false  false” will exclude it. This function is only really useful if we can reference each object upon which it works. We can use this by using the basic definition of this function (there is an extended one which we will discuss later). This accepts a DOM object representing the current element as a parameter. When referring to the jQuery 1.4.2. core, we see that it adopts the convention of naming the parameter elem:

    enabled: function(elem){
        return elem.disabled === false && elem.type !== "hidden";
    },

    disabled: function(elem){
        return elem.disabled === true;
    },

Who are we to argue? So now, our Custom Selector template becomes:

    $.extend($.expr[":"], {
        selectorName:function(elem){
            return [boolean expression];
        }
    });

So, returning to our original example of wanting to search for all elements with an empty val attribute, our code takes on the following form.

   $.extend($.expr[':'], {
       valueEmpty: function(elem) {
           var $elem= $(elem);
           return ($elem.val() === "") && ($elem.attr("type") === "text");
       }
   });

I’ve added a check to ensure the DOM element is a text box, and I’ve cached the jQuery cast of elem to avoid multiple calls into the library. Really, the implementation is secondary to the discussion here. The important thing to note is that it will return a Boolean. Calling out new code is trivial, and as we would expect:

    alert($(":valueEmpty").length); 

Although, I always advocate combining low-performance selectors (of which this is one) with higher performance ones (more on this later):

    alert($("input:valueEmpty").length); 

Parameterised Custom Selectors You’ll notice that some Pseudo-Class selectors accept a parameter, for example :has(selector). So how do we get some of that good stuff? We are going to build a lengthBetween selector that will filter out items whose length is greater than two specified parameters, in this case, four and eight. The calling code will look like:

    alert($("input:lengthBetween(4,8)").length);

The anonymous function we specified for our original custom selector actually has four parameters. We only used the first, elem. The following is the full definition:

     $.extend($.expr[":"], {selectorName:function(elem, i, match, array){
        return [boolean expression];
     });

So what are all of these parameters?

  • elem we are already familiar with - it is the current DOM element of the iteration stack
  • i is the index of elem upon the stack
  • match is an array that contains all information about the custom selector
  • array contains all the elements in the stack over which we are iterating

We are interested in the match array parameter, as this is where we will retrieve parameter information. The match array stores four pieces of information. So, given the the selector call:

    alert($("input:lengthBetween(4,8)").length);


  • match[0] – contains the full pseudo-class selector call. In this example :lengthBetween(4,8)
  • match[1] – contains the selector name only. In this example lengthBetween
  • match[2] – denotes which, if any, type of quotes are used in the parameter expression. i.e. single (‘)  or double (“). In this example it will be empty.
  • match[3] – gives us the parameters, i.e. what is contained in the brackets. In this example 4,8

So, if we just want the parameters, then match[3] is the way forward. This is a simple string value and it’s really up to you how you handle it. You can String.Split() it to get multiple parameters, and you can consider validating the parameters somehow. Again, we are drifting away somewhat from the scope of this discussion, so I’ll refer to the jQuery core once more:

    gt: function(elem, i, match){
        return i > match[3] - 0;
    },

Here, a single parameter is expected and assumed. No validation attempt is made. So, returning to our :lengthBetween selector, the implementation might look something like:

    $.extend($.expr[":"], {
        lengthBetween: function(elem, i, match) {
         var params = match[3].split(",");  //split our parameter string by commas
         var elemLen = $(elem).val().length;  //cache the length of the current element to cut out multiple calls
         return ((elemLen >= params[0] - 0) && (elemLen <= params[1] - 0));  //perform our check
        }
    });

So there we have it - A custom selector that will filter out values whose length is between one and three characters.

Speed and Efficiency

I have always encouraged developers to consider the speed and efficiency of their basic selectors. Although it is not an exact science (relative speeds can differ between browsers, and selector combinations can be unpredictable), I have always advocated the following rule of thumb when it comes to using your selectors:

  1. An #ID selector is quicker than element selector is quicker than .class selector.
  2. Always try to prefix .class selectors with an element selector
  3. #ID selectors almost always can be used in isolation.

For further reading, Hugo Vidal Teixeira has provided a nice analysis of jQuery selector performance.

So where do pseudo-class and custom selectors fit into this? An #ID and element selector map directly to the core JavaScript functions .getElementById() and .getElementsByTagName(). Class, Pseudo-Class and Custom selectors all require a scan of the DOM to filter out elements, which is inherently slow.

So, treat custom selectors like class Class and Pseudo-Class selectors when it comes to performance.

Resources / Further Reading

Some useful links for further reading and other custom selectors.

http://james.padolsey.com/javascript/extending-jquerys-selector-capabilities/

http://code.google.com/p/aost/wiki/CustomJQuerySelectorInTellurium

http://jquery-howto.blogspot.com/2009/06/jquery-custom-selectors-with-parameters.html

And Finally…

What of jQuery.expr[':']?

The eagle eyed among you might have questioned as to why we should be constrained to use just the colon? In my opinion, this is straying into dangerous territory, however it is possible given the versatility of the Sizzle selector engine. You can read more in this article, which documents how to override the ‘<’ symbol.

,