jQuery filter

Earlier, we talked about selector filters that help us produce better selections. jQuery also has special methods for filtering that actually have the same effect as selector filters.

Filter method

The method filter(condition) takes a filtering condition as a parameter. And if the elements of the sample do not meet this condition, then they are excluded from the sample. Depending on what the condition is, this method has the following use cases:

  • filter(selector): if the objects of the selection do not satisfy the selector, then they are excluded
  • filter(element): if the selected objects do not represent the given HTML element, then they are excluded
  • filter(jQuery): if selection objects do not represent the given jQuery object, then they are excluded
  • filter(function): a function is called for each element of the selection, and if this function returns false, then the element is excluded from the selection

For example, let’s select all elements with the attribute class=”header” that are also table row elements:

 
$(function(){
    //Filtering by selector
    var array = $(".header").filter("tr");
    array.css('background-color', 'silver');
    
    // Filter by html element
    varelem = document.getElementsByTagName("tr")[0];
    var array1 = $(".header").filter(elem);
    array1.css('background-color', 'silver');
});

This option is an analog of the expression $(“tr.header”), so we can again achieve the same result by combining selectors.

Now let’s see how to use the function.

  
$(function(){
    var array = $("tr").filter(function(){
        if($(this).hasClass("header")) { return true;}
        else {return false;}
    });
    array.css('background-color', 'silver');
});

First, the function is called for each element, and we get the current element using the expression $(this). Next, using the method hasClass(“header”), we determine whether the current element contains the header class. And if it does, then we return true.

not method

The opposite of the filter method is the not. It excludes from the selection those elements that match the condition. This method can have the following use cases:

  • not(selector): if the objects in the selection match the selector, then they are excluded
  • not(element): if the select objects represent the given HTML element, then they are excluded
  • not(jQuery): if select objects represent the given jQuery object, then they are excluded
  • not(function): a function is called for each element of the selection, and if this function returns true, then the element is excluded from the selection

For example, we can replace filter with the not method in the previous example and then we will get the opposite result:

 
$(function(){
    var array = $("tr").not(function(){
        if($(this).hasClass("header")) { return true;}
        else {return false;}
    });
    array.css('background-color', 'silver');
});

slice method

The method slice(begin, end) excludes from the selection those elements that do not fall within the range specified by the begin and end parameters. Indexing is assumed to start at 0. Negative indices mean that the sample is taken from the end of the set. The optional parameter end specifies the position from which the selection of elements has already been terminated, if this parameter is absent, then the selection is continued until the end of the set:

 
$(function(){
    var array = $("tr").slice(1,4);
    array.css('background-color', 'silver');
});

In this case, the final selection will contain 3 tr elements.

The second version of the slice function involves setting one parameter – the initial index from which the selection is made:

 
$(function(){
    var array = $("tr").slice(3);
    array.css('background-color', 'silver');
});

In this case, the selection will include all objects, starting from the 4th one.

has method

The method has(nested element)checks the object for the presence of a nested element. And if the object contains a nested element, then this object remains in the selection. It can have the following call options:

  • has(selector): if objects contain an element that matches the selector, then they remain in the selection
  • has(element): if the objects contain the given HTML element, then they remain in the selection

For example, we have a list with nested lists on the page. And we need to select the element of the list that has a nested list:

  
<ul>
    <li>Point 1</li>
    <li>Item 2
        <ul>
            <li>Subclause 2.1</li>
            <li>Subclause 2.2</li>
        </ul>
    </li>
    <li>Item 3</li>
</ul>

Then we can use the following expression:$(‘li’).has(‘ul’).css(‘background-color’, ‘silver’);

Sample transformation and the map method

The method map(callback)is designed to convert the elements of the selection using the function that is passed in the parameter callback. And this function selects elements from the existing set for a new set and returns this new set at the output. Let’s use the example with nested lists:

  
<ul>
    <li>Point 1</li>
    <li>Item 2
        <ul>
            <li>Subclause 2.1</li>
            <li>Subclause 2.2</li>
        </ul>
    </li>
    <li>Item 3</li>
</ul>

Now we select only those elements that have nested lists:

 
$(function(){

    var array = $('li').map(function(index,elem){
        return $(elem).children()[0];
    });
    
    array.each(function(index, elem){
        console.log(elem.innerHTML);
    });
    array.css('background-color', 'silver');
});

The function passed to the map method runs through all the elements of the selection and takes two parameters: index – the index of the element to be sorted out in the selection, and elem – the element to be iterated over. Having received the current element during the iteration, we can perform some manipulations with it and determine whether it or some other elements should fall into the new selection.

So, in this case, we’re passing the iterated element to a jQuery function so that jQuery methods are available to us, and we get the first nested list: $(elem).children()[0];(the children method helps get nested or child elements).

We can then manipulate the result set just like any other selection, such as iterating, setting properties, and so on.

is method

The method is (condition) determines whether there are objects in the given selection that match the condition. Depending on the condition, this method has the following use cases:

  • is(selector): checks if at least one select object matches the selector
  • is(element): checks if the given HTML element is present in the selection
  • is(jQuery): checks if the given jQuery object is present in the selection
  • is(function): search in the selection of objects corresponding to the given HTML element

At the output, the is method returns a boolean value: true if at least one element of the selection matches the condition, and false if no such match is found. For example, we have this markup:

  
<ul class="menu">
    <li>Point 1</li>
    <li>Item 2
        <ul class="submenu">
            <li>Subclause 2.1</li>
            <li>Subclause 2.2</li>
        </ul>
    </li>
    <li>Item 3</li>
</ul>

We use the is   method:

 
  var lists = $('ul');
    if(lists.is('.submenu')){
        lists.css('background-color', 'silver');
    }
    

Since one of the list items contains a nested sublist with the submenu class, the is method will return true and hence the entire list will be filled.