jQuery has a powerful collection of selectors which make selecting a specific collection of elements much simpler. Among my favorites are :text, which matches one-line text inputs, and :checked, for determining what checkboxes in a group have been selected. But sometimes our filter criteria relies on domain specific information.
Take for example an alumni foundation seeking to target all alumni who donated at least $1,000 last year. Their donor database provides them a table of alumni showing their 2008 donations, like this:
It would be great if we could select these rows easily in jQuery. From there we could remove the others who donated less than $1k from the list, or highlight the ones who did. Ideally, we’d like to do something like this:
1 | |
Of course, “bigdonor” isn’t a real selector, but jQuery makes it trivial to change that. All we must do is define the bigdonor selector, and provide an expression which returns true if the given object is a match, and false if not. Here’s the code:
1 2 3 4 5 6 | |
Explanation:
The first line starts a call to jQuery.extend(), which is a function that allows us to add functionality to jQuery and is the basic way we implement plugins. In the case of a plugin we would extend the jQuery object itself, but in this case we want to extend jQuery’s “:” expression.
Line 4 is where we actually define our custom selector. jQuery already has a list of predefined selectors just like this, and we’re just adding another to the list. Selectors come in two parts, separated by a colon: a symbol, and an expression which must evaluate to true or false. In our case “bigdonor” is the symbol, and the expression is the code in quotes. There’s a bit going on there that’s worth explaining:
In the context of selectors, a is an object which represents the current element. Its equivalent to this in other contexts. So this code looks for the last td element contained by the current element, converts its inner HTML into an integer, and then returns whether or not the result is at least 1000.
With our new selector defined, our original code works as intended. Here it is again:
1 | |
The resulting table might look something like this:
Thats it! Our example is fairly basic, but hopefully you’ve already thought of some ways this can come in handy for your own projects. We find them especially useful for enhancing legacy web apps without modifying the underlying codebase.