How to Create Custom Filters in Jquery

by admin Date: 17-12-2013 jquery css resources tutorials tips plugins snippets webdev

If you are a web designer or a developer you frequently need a shortcut to collect elements for jQuery.

In this post, based on the book Instant jQuery Selectors, you’ll learn how to build a custom filter in jQuery.

So, we try to built a filter that ia able to print the length of the elements that have the placeholder attribute set, taking advantage of a previously created custom filter. In addition, to see all of the available options in action, we’ll create a second filter to collect all of the elements having a name with less than a given number of characters.

Well, we have to follow 4 steps:

Step 1

Create a file using a simple text editor, like Notepad++ and rename it as custom-filters.html.

Step 2

Then, we’ll create a simple form with the typical fields like “Name”, “Surname”... All these fields have the specification of the type (type attribute) and the name (name attribute), but few of them also have a placeholder set (placeholder attribute).

<!DOCTYPE html>
      <meta charset="UTF-8">
      <title>Instant jQuery Selector How-to</title>
            display: block;
      <!-- Script will be placed here... -->
      <form name="registration-form" id="registration-form" action="registration.php" method="post">
         <input type="text" name="name" placeholder="Name" />
         <input type="text" name="surname" placeholder="Surname" />
         <input type="email" name="email" placeholder="Email" />
         <input type="tel" name="phone-number" placeholder="Phone number" disabled="disabled" />
         <input name="privacy" type="checkbox" checked="checked" />
         <label>Contact me:</label>
         <input name="contact-me" type="checkbox" />
         <select name="sex">
            <option selected="selected" value="m">Male</option>
            <option value="f">Female</option>
         <input type="submit" value="Register" />

Step 3

Replace the comment we put in the HTML () with the following code:


<script src=""></script>
    $.expr[':'].placeholder = function(elem) {
        return $(elem).attr('placeholder') !== undefined;
    $.expr[':'].nameLengthLessThan = 
    $.expr.createPseudo(function(filterParam) {
        var length = parseInt(filterParam);
        return function(elem, context, isXml) {
            return $(elem).attr('name') !== undefined && 
            $(elem).attr('name').length < length;
    $(document).ready(function() {

Step 4

Save the file and try to open it with whatever browser. Then, look at the console’s output.

How it works

At the very beginning of our Script, we’ve added a property, or more specifically a function called placeholder to the :  attribute that belongs to the jQuery’s expr attribute. : is a property containing jQuery’s native filters and you can use it to add your own at runtime.

Inside the function definition, we just have a single statement that checks if the current element has the placeholder attribute set, and if so, it returns true to keep the element.

As you can see from the example, a filter is a function that accepts as an argument the current DOM element to process and needs to return true to keep it in the collection, and false to discard it.

You should use this method for creating a filter when the following are true:

  • You’re interested only in the element to process itself
  • The filter doesn’t accept an argument
  • The context to which the selection is applied doesn’t matter

The second filter, nameLengthLessThan, is a bit more complicated and uses the method introduced starting from jQuery 1.8 by witch we pass an anonymous function to the create a pseudo function having a parameter that represents the argument passed to the filter when you use it.

Then, inside it, we create another function that will be returned and that is responsible for performing the filtering.

Finally, jQuery passes the element to be processed (elem parameter), the DOM Element or DOM Document from which selection will occur (context parameter), and a Boolean that tells if you’re operating on an XML document.

This filter needs this pattern because our filter needs to know the limit of characters the name attribute of the element must comply with.

In other words, we need to pass the number of characters the value of the name attribute must respect.

Inside the inner-most function, we write the code to test if the element should be kept or not. For our example, this means checking whether the name attribute is set and its length is not less than the given length (stored using a closure inside the length variable).

Now that we’ve created the filters, we need to use them. Inside the handler for the document.ready event, there are two statements. The first calls the placeholder filter without parameters and implicitly using the Universal selector. The second uses the nameLengthLessThan filter passing 5 as parameter and using the Element selector. Using the Element selector in the second call will result in a performance improvement. Running the code will result in the following being printed in the console:

4  1



original source:

by admin Date: 17-12-2013 jquery css resources tutorials tips plugins snippets webdev hits : 6850  

Related Posts

    How To Grow Your Small Business

    A business that stays still will stagnate. To be successful and to have a business to be proud of, you need to ensure that it grows. This is not always…

    CSS in JavaScript (CSS-in-JS) Vs CSS in CSS

    What actually is CSS-in-JS? You've certainly heard or read words like CSS-in-JS, Styled Components, Radium, Aphrodite and you're and you're stuck in limbo there, "why is it? I'm completely happy about CSS…

    Level Up Your JavaScript Skills: 12 basic notions

    If you are a developer at any level, understanding its basic concepts is crucial. This article highlights 12 basic concepts that are critical to understanding by any JS developer, but do…

    Is jQuery going to die in 2019?

    For a while, JQuery's relevance has been a topic of debate among web developers. We were curious as web developers interested in Javascript to know what others have to say…

    Best 5 Javascript NewsTicker Plugins

    Not all developers know the marquee tag of HTML, that allows you to create a scrolling piece of text or image displayed that is shown horizontally or vertically on the DOM.…

    Best 5 Frontend Development Topics in 2019

    Ah, a new year. A time of positivity, a time to restart. For new objectives and proposals. And in the world of developers, to look at the scenery and decide…

    A roadmap to becoming a web developer in 2019

    There are plenty of tutorials online, which won't cost you a cent. If you are sufficiently self-driven and interested, you have no difficulty training yourself. The point to learn coding…

    Best Javascript front-end hacking cheatsheets

    JavaScript has a extremely high potential to build cutting-edge web applications. But it's really hard to memorize it by heart. The JavaScript cheat sheets therefore act perfectly as a reminder…

    Tips for JavaScript Developers in 2019

    Another year is over and JavaScript is constantly changing. However, there are some tips that can help you write in 2019 clean and efficient code that scales. Below is a…

    Working with JSON in JavaScript

    JSON is short for JavaScript Object Notation and an easy - to - access way to store information. In short, it gives us a collection of human - readable data…

    JavaScript Basis: Syntax & Structure

    Programming languages are defined by rules. The syntax is what we follow when we write our code, which forms the logical structure of our programs. Let's dive right into the basic…

    The Absolute Beginner's Guide to Sass

    You've probably heard about CSS preprocessors before, whether it's Sass, LESS or Stylus, and they're all great tools to maintain your CSS, especially when you work with large codebases. For…

We use our own cookies and third-party cookies to improve our services, show products based on your preferences, analyse the browsing habits of our users, and enable interaction with social networks. Continuing to browse our sites implies full acceptance of their use. You can change your cookie setting or get more information here: Cookies policy .