Skip to main content

Extending jQuery :: Part 3 – Custom Selectors

By February 15, 2015Blog

As we have seen in the previous two articles on Extending jQuery :: Part 1 – Miniature Plugins and Extending jQuery :: Part 2 – Standalone Methods, jQuery provides us some nice ways to extend it’s functionality. However, a little known feature of jQuery is its ability to extend its selectors. Here we will take a look at how to do that.

You’ve surely used selectors a lot in jQuery. For the most part you’ve used simple things like $('$elem div:first'). There are many selectors jQuery provides but sometimes it’s nice to be able to create your own. Again the idea is to keep your clean and in it’s proper place. Let’s take a look at a simple example.

$.expr[':'].hasText = function(obj){
    return $(obj).html() !== ''
};

The setup for the selector is the $.expr[':'] object. Here we can overwrite or add methods which will than be available as selectors on our elements. In the above example we want to select all elements that have some text inside them. So we do a little check to see if html() is empty and return. We could then call:

$('.someClasses:hasText').doSomething();

This would select all elements that have text and allow us to further perform some actions on them.

This is just another handy tool to have on your tool belt and when you role your own mini plugin, standalone methods and custom selectors you will surely be a pro and standout with your ability to organize and write reusable and clean code.