filter()

filter(callback)

Returns a subset of a set. All elements for which the callback function returns true will be included in the result.

callback

A function used as a test for each element in the set. Filter() passes the iteration index and the current element to the callback function. In the scope of the callback function, this refers to the current element.

Example

The selector of the following script is li (list item), so the results object contains all list items in the template. The scripts filters the third and sixth line items from the results, taking advantage of the index that is passed to the filter function, and colors them red. It uses the modulus operator (%) to select every item with an index value that, when divided by 3, has a remainder of 2. (The index starts counting at zero.)

results.filter(function(index) {
        return index % 3 === 2;
}).css( "background-color", "red" );

filter(selector)

Returns a subset of a set. All elements matching the selector will be included in the result.

The difference between results.filter(selector) and query(selector, results) is that query() searches throughout the entire results while filter() only takes the top-level elements into account.

selector

A String containing a CSS selector. See https://www.w3schools.com/cssref/css_selectors.asp for CSS selectors and combinations of CSS selectors.

Example

The selector of the following script is tr (table row), so the object results contains all rows in the template. The scripts filters all even rows from the results and colors them red.

results.filter(":nth-child(even)").css("background-color", "red");