jQuery

jQuery Filter Example

The aim of this example is to have a look at the .fiter(); method of jQuery. What this method does is reduce the set of matched elements to those that match the selector or pass the function’s test.

In other words, the filter() method returns elements that match a certain criteria. It lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match will be returned. This method is often used to narrow down the search for an element in a group of selected elements.

If you are already familiar with the .not() method, then you probably understand this is the opposite method.

1. Document Setup

To begin, create a new HTML document and add the following basic syntax inside:

<!DOCTYPE html>
<html>
<head>
	<title>jQuery Filter Example</title>
</head>
<body>

<!-- HTML SECTION  -->


<!-- JAVASCRIPT SECTION  -->
<script src="jquery-1.11.3.min.js"></script>

<script type="text/javascript">

</script>

</body>
</html>

Notice that the jQuery library is linked locally. To download it, please go here.

Syntax

The basic syntax of this method is: $(selector).filter(criteria,function(index));

Criteria is optional. It specifies a selector expression, a jQuery object or one or more elements to be returned from a group of selected elements. Adding a function is also optional. It specifies a function to run for each element in the set. If it returns true, the element is kept. Otherwise, the element is removed.

2. Basic Application

Let’s now see the method applied in an example. First add some paragraph elements. Those will be the ones from which some will be filtered.

<!-- HTML SECTION  -->
<h3>Look at the filtered elements:</h3>
<p>They call me Jack, like the drink.</p>
<p class="one">I live in the Jungle, with the tigers.</p>
<p class="one">No one ever visits a mamooth by default.</p>
<p>Paragraphs are meant to be understood, not just read.</p>

In the JS section, after selecting the p element, we apply the filter() method to it and specify a class as an argument to the method, the ".one" class. These will then be the two elements on which several css properties are going to be added.

<!-- JAVASCRIPT SECTION  -->
<script type="text/javascript">
$(document).ready(function(){
    $("p").filter(".one").css({
        "text-transform": "uppercase",
        "font-weight": "bold",
        "color": "red"
    });
});
</script>

Notice the red, bold and uppercase text. Those are the elements filtered and styled.

A basic application of the filter method.
A basic application of the filter method.

3. Cases and Exmaples

In addition to the basic application, there are quite a few other examples of how the method can be used.

3.1 Using Pseudo Selectors

Not only can you filter classes, but also use pseudo selectors to capture certain elements. Look at the example below:

<ul>
    <li>Even List Item</li>
    <li>Odd List Item</li>
    <li>Even List Item</li>
    <li>Odd List Item</li>
    <li>Even List Item</li>
    <li>Odd List Item</li>
</ul>

As you can see, above we have an unordered list with six list items. And you can see the text corresponds to their even/odd relation. Notice that in programming languages counting actually begins with 0 and not 1. That might be confusing, but it is a standard rule on every programming language.

Now in the JS section, instead of entering a class as an argument to the filter method, we enter a pseudo-selector like this: .filter(":pseudo")

<script type="text/javascript">
$(document).ready(function(){
    $("li").filter(":odd").css({
        "background-color": "yellow",
        "width": "20%",
        "font-weight": "bold"
    });
});
</script>

The result would be:

Using Pseudo Selectors as Arguments
Using Pseudo Selectors as Arguments

3.2 Using Multiple Criteria

What if you wanted more than one filter applied? Well, you can just enter as many filters you want by separating with a comma. Let’s see an example:

<div>
    <h4 class="one">Class One Here</h4>
    <h4 id="two">Class Two Here</h4>
    <h4 class="three">Class Three Here</h4>
    <h4 class="four">Class Four Here</h4>
    <h4 id="five">Class Five Here</h4>
    <h4 class="six">Class Six Here</h4>
<div>

Here we added six h4 elements and gave all of them either a class or an id, in a random definition. Below, we’ll only be filtering elements with a class of ".three" and an id of "#five" like so:

<script type="text/javascript">
$(document).ready(function(){
    $("h4").filter(".three, #five").css({
        "background-color": "#c0392b",
        "padding": "1em",
        "color": "white",
        "width": "20%"
    });
});
</script>

The result in the browser would be:

Using Multiple Criteria
Using Multiple Criteria

3.3 Using a Function as an Argument

Specifying a function inside the .filter() method surely gives you a lot more power in aspects of what you can achieve filtering elements. Below we’ll have a look at a simple example where we use a function to select all elements in which the division by 3 would give us a remainder of 1. First add some list items:

<ul>
    <li>First List Item</li>
    <li>Second List Item</li>
    <li>Third List Item</li>
    <li>Fourth List Item</li>
    <li>Fifth List Item</li>
    <li>Sixth List Item</li>
</ul>

Next, specify the function inside the method and give it an index as the function parameter. After that, just return index % 3 == 1.

<script type="text/javascript">
$(document).ready(function(){
    $( "li" ).filter(function( index ) {
        return index % 3 === 1;
      }).css( "background-color", "yellow" );
});
</script>

The only li items for which the condition is true are the second (index = 1) and fifth (index = 4).

Using a Function as the Method Argument
Using a Function as the Method Argument

4. Conclusion

To conclude, the .filter() method enables an easy way to select and manipulate any DOM elements we need, by providing flexibility in adding multiple classes/id’s, using functions, pseudo-selectors etc.

It is useful in many cases when you want to differentiate elements from the whole scope and apply methods to them, in order to create a distinct view or behaviour for those particular elements.

5. Download

Download
You can download the full source code of this example here: jQuery Filter

Fabio Cimo

Fabio is a passionate student in web tehnologies including front-end (HTML/CSS) and web design. He likes exploring as much as possible about the world wide web and how it can be more productive for us all. Currently he studies Computer Engineering, at the same time he works as a freelancer on both web programming and graphic design.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button