Creating custom selectors with jQuery

I recently re-discovered a powerful, but mostly hidden feature of jQuery. If you’ve used jQuery for any length of time you’ve probably used filter selectors like :input, :visible or :hidden. What you may not know is, it is really simple to add your own filter selectors. The secret lies in $.expr.filters which is an object of filters. By adding into this object you can define new filters, or redefine existing ones. My specific case was I needed to filter elements to only those that could get tab focus. Defining a filter is simple and looks something like:

With only a few lines of code, you can create really expressive filters that let you write expressive selectors. As you can see above, filter functions get an element as their only argument. Filter functions should return a boolean, indicating whether the element passes or fails the filter’s criteria. You could use our new tabable filter by doing:

Hopefully you can find use for this powerful and somewhat hidden jQuery feature in future projects. They are a great way to add expressive ways to select/filter elements based on data stored in the DOM.

Comments

Nice! I’m often pleasantly surprised about jQuery’s extensibility. Another fun hidden one is cssHooks – getters and setters for css properties (and I imagine custom ones).

Recent Artwork

Links

Mark is a designer and web-developer, working with standards compliant HTML and CSS. He has been building websites since 2000. Currently he is employed at Freshbooks as a developer, and actively contributes to open source projects specifically CakePHP. He uses this site as a place to share what he has learned and made.