Creating Your Own jQuery Selector Creating Your Own jQuery Selector

By default, the jQuery selectors are pretty advanced. You can select items by classes, ids, attributes, the first, the last, etc… But why stop there? By simply extending jQuery, we can add our own custom selectors to further enhance how we use jQuery. In this example, I will create an extended function called widthOver300 leveraging jQuery's $.extend


Reviewing jQuery's toggle

Let's begin by looking at a basic, pre-existing, jQuery selector:


$(".myClass:first").toggle();

In the above code example, I am toggling the first element that jQuery finds with the class name of myClass. This will either show or hide the element based on it's current display CSS property.

Creating a jQuery selector

Now, what if I want to find an element with the name of myClass that has a width of over 300 pixels? It would be nice to do something like this:


$(".myClass:widthOver300").toggle();

This can be accomplished with a nice little jQuery extension as follows:


$.extend($.expr[":"], {
widthOver300: function (e)
{
return $(e).width() > 300;
}
});

With the above code added, if I re-run the previous example, all elements with the class name of myClass that have a width of more than 300 pixels will be toggled on or off.

By extending jQuery, you can add custom selectors to help make your code more readable and reusable. Simply be sure to check jQuery first so that selector doesn't already exist as you wouldn't want to reinvent the wheel!

Published on Mar 16, 2019

Tags: extend | JavaScript | jQuery Tutorial

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.