Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the "match" object in a Custom Filter Selector in jQuery 1.8

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:

  1. The element in question

  2. The index of this element among the entire collection

  3. 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:

  1. Is this expected behavior? Is it documented anywhere?

  2. 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")?

  3. 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.

like image 574
Joseph Silber Avatar asked Jul 24 '12 04:07

Joseph Silber


People also ask

Which one of the given jQuery methods filters out elements from a set of matched elements?

jQuery filter() Method This method lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match will be returned. This method is often used to narrow down the search for an element in a group of selected elements.

What is TD EQ in jQuery?

jQuery :eq() Selector The :eq() selector selects an element with a specific index number. The index numbers start at 0, so the first element will have the index number 0 (not 1). This is mostly used together with another selector to select a specifically indexed element in a group (like in the example above).


2 Answers

jQuery has added a utility for creating custom pseudos in Sizzle. It's a little more verbose, but it's much more readable than using match[3]. It also has the advantage of being more performant as you can avoid repeating tedious calculations every time an element is tested. The answer that has already been accepted is a good answer, but let me add a note to say that you can use $.expr.createPseudo instead of setting the sizzleFilter property yourself, which will save a little space.

jQuery.expr[':'].tabIndexAbove = $.expr.createPseudo(function( tabindex ) {
    return function(elem) {
        return +elem.getAttribute('tabindex') > tabindex;
    }
});

$('input:tabIndexAbove(4)').css('background', 'teal');

jsfiddle: http://jsfiddle.net/timmywil/YCsCm/7/

This is all documented on Sizzle's github: https://github.com/jquery/sizzle/wiki/Sizzle-Documentation

like image 189
timmywil Avatar answered Oct 22 '22 03:10

timmywil


By looking at the jQuery 1.8 beta2 source and the "Extensibility" section of The New Sizzle, you have to set fn.sizzleFilter to true in order to get the pseudo argument and the context. If not, you'll just get all the elements in the arguments.

Here is the code that does the same thing as your example. Use the selector parameter passed in the function to get the pseudo argument.

Here is the working example on jsfiddle.

As mentioned in the blog post above, you can even pre-compile and cache the your selector.

var sizzle = jQuery.find;

var tabIndexAbove = function( selector, context, isXml ) {
    return function( elem ) {
        return elem.getAttribute("tabindex") > selector;
    };
};

/*
 fn.sizzleFilter is set to true to indicate that tabIndexAbove 
 is a function that will return a function for use by the compiler 
 and should be passed the pseudo argument, the context, and 
 whether or not the current context is xml. If this property is 
 not set, adding pseudos works similar to past versions of Sizzle
*/
tabIndexAbove.sizzleFilter = true;
sizzle.selectors.pseudos.tabIndexAbove = tabIndexAbove;

$('input:tabIndexAbove(4)').css('background', 'teal');

Just a note, if you're looking at the source, jQuery slightly changed the structure that the public-facing interface points to.

In jQuery 1.7.2:

jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;

In jQuery 1.8b2:

jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
like image 23
322896 Avatar answered Oct 22 '22 04:10

322896