Hiren Sharma

jQuery Fever: Extending jQuery with Custom Selectors

jQuery nowadays is a part of every project. Developers write hundreds of lines of code, sometimes thousands. Even you must must be doing so. Do you ever feel like extending it, customizing it as per your needs. Well, writing plug-ins is not the only way you can extend jQuery, but you can also write your custom selectors. I’ll cover jQuery plug-ins in the upcoming posts but for now, let’s concentrate on extending selectors.

Even for me, not even a single day passes by when i don’t use the write-less do-more library. With increased usage, you often find yourself writing complex selectors which are being used multiple times in your project. You don’t have any choice but write the same complex syntax again and again. What if you have to change those selectors, will you go and change in each and every js file. Well I guess you don’t have any other choice, unless you write one of your own. So let’s see how you can write a custom selector to suit your needs.

Custom Selector Template

Generic syntax you use while creating a custom jQuery template is:

$.extend($.expr[‘:’], { customSelectorName: function(currentobject, currentindex, metadata, elementcollection) {                                                        //return true/false to include/exclude current element
}
});

And corresponding syntax to use the custom selector is:

$(".randomClassSelector:customSelectorName").randomOperation();

And yes, it’s that simple. To clarify more, let’s take some examples:

Example 1:

Let’s write a selector to select all elements with no background color or transparent background.

$.extend($.expr[':'], {
     transparent: function(currentobj) {
           // If following condition is true, the element
           // will be added to the resulting stack, else not
           return $(currentobj).css('background-color) ==='transparent';
     }
});

$(“div:transparent”); // SELECTOR USAGE

You can see this Script in Action

Example 2

Let’s try something more complex now.

$.extend($.expr[':'], {
     opacity: function(currentobj, index, metadata){
           // We need metadata to get opacity value, which will be passed
           // in parenthesis while writing selector
           return ($(currentobj).css("opacity") == metadata[3]);   // Metadata[3] always contains
                                                                        //the value passed
      }
});

$(“div:opacity(0.3)”); // Will get Divs whose opacity is set to 0.3

You can see this Script in Action

This is just the beginning guys like i say always, jQuery selectors have no barries, no limitations. You can use parent, child, height, width or any other css or dom property to write your own custom selectors. So go ahead and try out some other complex selectors for yourself.

Do share your feedback in comment box below.

To your Coding Success !!!