To filter a selection you can use the .filter()
method.
The method is called on a selection and returns a new selection. If the filter matches an element then it is added to the returned selection, otherwise it is ignored. If no element is matched then an empty selection is returned.
This is the HTML we will be using.
<ul>
<li class="zero">Zero</li>
<li class="one">One</li>
<li class="two">Two</li>
<li class="three">Three</li>
</ul>
Filtering using selectors is one of the simpler ways to filter a selection.
$("li").filter(":even").css("color", "green"); // Color even elements green
$("li").filter(".one").css("font-weight", "bold"); // Make ".one" bold
Filtering a selection using a function is useful if it is not possible to use selectors.
The function is called for each element in the selection. If it returns a true
value then the element will be added to the returned selection.
var selection = $("li").filter(function (index, element) {
// "index" is the position of the element
// "element" is the same as "this"
return $(this).hasClass("two");
});
selection.css("color", "green"); // ".two" will be colored green
You can filter by DOM elements. If the DOM elements are in the selection then they will be included in the returned selection.
var three = document.getElementsByClassName("three");
$("li").filter(three).css("color", "green");
You can also filter a selection by another selection. If an element is in both selections then it will be included in the returned selection.
var elems = $(".one, .three");
$("li").filter(elems).css("color", "green");