Make Your Own Custom jQuery Selector

Share this article

Of all the JavaScript libraries out there, jQuery arguably has the selector syntax closest to CSS, and that makes it easy for CSS authors to dive in, even though there are 52 selectors to choose from. If you like CSS’s :first-child, :hover, or :only-child, there are 34 similar “pseudo” pseudo-class selectors on the menu. Talk about spoiled for choice!Should you want more than jQuery’s native selectors—such as :animated, :even, :not(), and :visible—there’s a raft of custom selectors from the community (like :exactIgnoreCase(), :nothidden, or :loaded()) to fill any gaps.So this all means that there’s no need for you to worry about learning to write custom selectors—right? Wrong!The easier a task is to complete, the greater the chance that it will be completed. Here’s a test for you to try out: ask a new developer to use (let alone understand) this code:

if ($(el).offset().top > $(window).scrollTop() - $(el).outerHeight(true) &&    $(el).offset().top < $(window).scrollTop() + $(el).outerHeight(true) + $(window).height()){  //do something}
Now ask them to try this on for size:
if ($(el).is(":inview")) {  //do something}
No prizes for working out that each of those snippets does the same thing, and that the second version is going to see much more use. Both check to see if an element is currently in the viewport.If you find yourself with a lengthy condition to get a Boolean, or your true/false Boolean is showing up again and again, you might be on target to create a custom expression for your selector. And making them could hardly be easier:
jQuery.extend(jQuery.expr[':'], { //$.extend($.expr[':'] is just as good  expression: function () {    //establish boolean to be returned, or    return false;  }});
The expression is what will be called in your selector … it could be inview, loaded, or nothidden.The function is what you’d expect. We’ve added the return false
, as that’s what you want the function to do at the minimum. Other than that, use any methods you need to return the Booleans that will power your selector.Let’s have a first run at our inview selector:
jQuery.extend(jQuery.expr[':'], {  inview: function (el) {    if ($(el).offset().top > $(window).scrollTop() - $(el).outerHeight(true) &&        $(el).offset().top < $(window).scrollTop() + $(el).outerHeight(true) + $(window).height()) {      return true;    }    return false;  }});
The code is far from optimized, but it’s working. For testing, I like to add selectors in their own script block between the jQuery include and my working script block. For production, though, you can include them like a plugin. Go ahead and add it to a page, and you can use it in several ways:
$("p:inview").css("color","orange");
or
$("p").filter(":inview").each(function(){  //do something});
or
if ($("p#desc").is(":inview")) {  //do something}
Now let’s take a look at some optimizations. Straight out of the box we can see some repetition that we can cache, including some repeated objects. As we’re only returning true or false, we can simply return our condition and we’ll be on our way:
jQuery.extend(jQuery.expr[':'], {  inview: function (el) {    var $e = $(el),    $w = $(window),    top = $e.offset().top,    height = $e.outerHeight(true),    windowTop = $w.scrollTop(),    windowScroll = windowTop - height,    windowHeight = windowTop + height + $w.height();    return (top > windowScroll && top < windowHeight);  }});
And we’re there! We’ve extended jQuery’s expression engine and our code is both optimized and readable.It’s not the only “in view”-style selector you’ll find on the Web, but ours is an evolution. It takes the height of the element into account, so that it keeps reporting true as long as the element is partially in the viewport.jQuery’s selectors are a natural for customization, and give you a great way to wet your feet before jumping into using .extend() to make plugins.
Note: Want more?
If you want to read more from Craig, check out jQuery: Novice to Ninja, the book he co-wrote with Earle Castledine.

Frequently Asked Questions about Custom jQuery Selectors

How can I create a custom jQuery selector?

Creating a custom jQuery selector involves extending the jQuery.expr[‘:’] object. This object contains all the custom jQuery selectors. To create a new one, you simply add a new property to the jQuery.expr[‘:’] object. The property’s name will be the name of your custom selector, and its value will be a function that defines the selector’s behavior. This function should take three arguments: an element, an index, and a match array. It should return true if the element matches the selector, and false otherwise.

What are the benefits of using custom jQuery selectors?

Custom jQuery selectors can make your code more readable and maintainable. They allow you to encapsulate complex selection logic in a single, reusable selector. This can reduce code duplication and make your code easier to understand. Additionally, custom selectors can improve performance by reducing the number of DOM traversals.

Can I use custom jQuery selectors with other jQuery methods?

Yes, custom jQuery selectors can be used with any jQuery method that accepts a selector string. This includes methods like .find(), .filter(), .not(), and .has(). This allows you to use your custom selectors in a variety of contexts and makes them a powerful tool for manipulating the DOM.

Are there any limitations to using custom jQuery selectors?

While custom jQuery selectors are a powerful tool, they do have some limitations. They can’t be used with CSS pseudo-classes or pseudo-elements, and they can’t be used with the :has() selector. Additionally, they may not perform as well as built-in selectors in some cases, especially when used with large DOM trees.

How can I debug a custom jQuery selector?

Debugging a custom jQuery selector can be done using the browser’s developer tools. You can use the console to test your selector and see which elements it matches. If your selector isn’t working as expected, you can use the debugger to step through your selector function and see where it’s going wrong.

Can I use custom jQuery selectors in older versions of jQuery?

Custom jQuery selectors are supported in all versions of jQuery. However, the syntax for creating custom selectors has changed slightly in jQuery 1.8 and later. In these versions, you should use the jQuery.expr.pseudos object instead of the jQuery.expr[‘:’] object to define your custom selectors.

Can I use custom jQuery selectors with jQuery plugins?

Yes, custom jQuery selectors can be used with jQuery plugins. However, you should be aware that some plugins may not work correctly with custom selectors, especially if they rely on specific built-in selectors.

How can I optimize the performance of my custom jQuery selectors?

There are several ways to optimize the performance of your custom jQuery selectors. One way is to limit the scope of your selectors by using a context parameter or by chaining them with other selectors. Another way is to avoid unnecessary DOM traversals by using efficient selector expressions.

Can I create a custom jQuery selector that selects elements based on their attributes?

Yes, you can create a custom jQuery selector that selects elements based on their attributes. The function that defines your custom selector can access the attributes of the element it’s testing using the element’s getAttribute method.

Can I share my custom jQuery selectors with other developers?

Yes, you can share your custom jQuery selectors with other developers. You can do this by packaging your selectors into a jQuery plugin, or by simply sharing the code that defines your selectors. However, you should make sure to document your selectors well so that other developers understand how to use them.

Craig SharkieCraig Sharkie
View Author

A degree in Fine Art is a strange entrance to a career with a passion for programming, but that's where Craig started. A right-brain approach to code and problem solving has seen him plying his craft for many of the big names of the web - AOL, Microsoft, Yahoo!, Ziff-Davis, and now Atlassian.

jQuerypluginsselectors
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week