December 28, 2011

jQuery Selectors

jQuery is a great tool for Javascript development.  Personally, I think the best part about this framework are the selectors.  If I want to get all paragraph elements on the page, I simple write: $('p').  Easy, right?

But jQuery offers so much more in traversing the DOM.  We can select all the odd paragraph elements as well by simply writing: $('p:odd').

Now, if I want to, I can even make my own selectors!  If I want to find all elements that are "shorter" than 10 pixels, I can write a custom selector.  There are a couple of ways you can write a selector, but I like the following template:

$.extend($.expr[":"], {
    newexpression : function (obj, index, meta, stack) {
        return boolean;

And it's just that simple.  For example, if I want to get all "short" elements, I can extend jQuery's functionality as such:

$.extend($.expr[":"], {
    short : function (obj, index, meta, stack) {
        return $(obj).height() < 10;

Then we can use it like so:



Post a Comment