Skip to main content

Be Cool and Write Your Own jQuery Selectors

Sam Deering

Be Cool and Write Your Own jQuery Selectors

jQuery has loads of built-in selectors for selecting elements (by ID, class, tag, attribute etc) but wouldn’t you like to be clever and start creating your own jQuery selectors? Well, it’s quite easy, this is how you can do it!

“Most developers usually add classes to our markup and then reference them using jQuery. But another way is to create your own selectors by extending jQuery!”

Lets say you wanted to select all elements that are over 100 pixels in height. This is how you could create a selector to do that for you!

//Define the custom selector
$.extend($.expr[':'], {
    over100pixels: function(a) {
        return $(a).height() > 100;
//Use it on an event to any element you click that is over 100 pixels high
$('div:over100pixels').click(function() {
    alert('The element you clicked is over 100 pixels high');

That’s it! The sky is the limit with custom jQuery selectors so start climbing that ladder!