Creating a Custom Filter Selector - J Query

Problem
You need a reusable filter to target specific elements based on their characteristics. You want something that is succinct and can be included within your selector expressions.

Solution

You can extend jQuery’s selector expressions under the jQuery.expr[':'] object; this is an alias for Sizzle.selectors.filters. Each new filter expression is defined as a property of this object, like so:

The function will be run on all elements in the current collection and needs to return true (to keep the element in the collection) or false (to remove the element from the collection). Three bits of information are passed to this function: the element in question,the index of this element among the entire collection, and a match array returned from a regular expression match that contains important information for the more complex expressions.
For example, you might want to target all elements that have a certain property. This filter matches all elements that are displayed in line:

Now that we have created a custom selector, we can use it in any selector expression:

Discussion

As mentioned, the third parameter passed to your filter function is an array returned from a regular expression match that jQuery performs on the selector string. This match is especially useful if you want to create a filter expression that accepts parameters. Let’s say that we want to create a selector that queries for data held by jQuery:

The purpose of the selector would be to select all elements that have had data attached to them via jQuery’s data() method—it specifically targets elements with a data key of something, equal to the number 123.

The reason for such a complex regular expression is that we want to make it as flexible as possible. The new selector can be used in a number of different ways:

Now we have a totally new way of querying data held by jQuery on an element.
If you ever want to add more than one new selector at the same time, it’s best to use
jQuery’s extend() method:


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics