For reference, here's an article on Creating a Custom Filter Selector with jQuery.
Introduction:
For those not familiar with jQuery's Custom Filter Selectors, here's a quick primer on what they are:
If you need a reusable filter
, you can extend jQuery’s selector expressions by adding your own functions to the jQuery.expr[':']
object.
The function will be run on each element in the current collection and should return true or false (much like filter
). Three bits of information are passed to this function:
The element in question
The index of this element among the entire collection
A match
array returned from a regular expression match that contains important information for the more complex expressions.
Once you've extended jQuery.expr[':']
, you can use it as a filter in your jQuery selector, much like you would use any of the built-in ones (:first
, :last
, :eq()
etc.)
Here's an example where we'll filter for elements that have more than one class assigned to them:
jQuery.expr[':'].hasMultipleClasses = function(elem, index, match) {
return elem.className.split(' ').length > 1;
};
$('div:hasMultipleClasses');
Here's the fiddle: http://jsfiddle.net/acTeJ/
In the example above, we have not used the match
array being passed in to our function. Let's try a more complex example. Here we'll create a filter to match elements that have a higher tabindex
than the number specified:
jQuery.expr[':'].tabindexAbove = function(elem, index, match) {
return +elem.getAttribute('tabindex') > match[3];
};
$('input:tabindexAbove(4)');
Here's the fiddle: http://jsfiddle.net/YCsCm/
The reason this works is because the match
array is the actual array returned from the regex that was used to parse the selector. So in our example, match
would be the following array:
[":tabIndexAbove(4)", "tabIndexAbove", "", "4"]
As you can see, we can get to the value inside the parentheses by using match[3]
.
The Question:
In jQuery 1.8, the match
array is no longer being passed in to the filter function. Since we have no access to the info being passed in, the tabindexAbove
filter does not work anymore (the only difference between this fiddle and the one above, is that this uses a later version of jQuery).
So, here are several points I'd like clarified:
Is this expected behavior? Is it documented anywhere?
Does this have anything to do with the fact that Sizzle
has been updated (even though it clearly states that "the old API for Sizzle was not changed in this rewrite". Maybe this is what they mean by "the removal of the now unnecessary Sizzle.filter
")?
Now that we have no access to the match
array, is there any other way to get to the info being passed in to the filter (in our case, 4
)?
I never found any documentation in the jQuery Docs about the custom filter selectors, so I don't know where to start looking for information about this.
See Question&Answers more detail:
os