January 7, 2010 | In: jQuery

Extending jQuery: Custom Selectors

I came across this question on StackOverflow the other day.  And my first reaction was huh?  My second was, of course!  Brilliant!

One of the keys to writing effective jQuery is being able to write effective selectors.  It’s really one of those things that you just get better at with experience.  But what happens when you have some common set of selectors you find your self always writing.  Well, you can extend jQuery using custom selectors.

A simple example:

Problem:

You often do form validation in jQuery and you always need to identify empty fields on a form.  Your simple form:




    
    


Some Form

Thing 1 Thing 2 Thing 3

Solution:

You could write some simple validation function that might look like this:

function ValidateForm() {
 $('span.validation_error').remove();
 $(':text').each(function() {
    if ($(this).val() == '') {
     $(this).after('*');
    }
  })
}

That would work sufficiently.  But wouldn’t it be nicer and more readable to be able to write:

function ValidateForm() {
 $('span.validation_error').remove();
 $(':textEmpty').each(function() {
  $(this).after('*');
   })
}

Unfortunately there is no :textEmpty selector.  But no problem, we’ll just create one:

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

function ValidateForm() {
    $('span.validation_error').remove();
    $(':textEmpty').each(function() {
       $(this).after('*');
    })
}

Summary:

As you can see it’s relatively trivial to extend jQuery’s selectors.  Of course you don’t need to have your custom selectors defined in the $(document).ready().  You could just as easily create your own file with all your most commonly used selectors in it.

And to say this is just the tip of this iceberg is an understatement.  James Padolsey has a great listing of different ways to extend jQuery selectors.

Comment Form