MOCKSTACKS
EN
Questions And Answers

More Tutorials









Jquery Filter a selection


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.

The HTML


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>

Selector


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

Function


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

Elements


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");

Selection


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");


Conclusion

In this page (written and validated by ) you learned about Jquery Filter a selection . What's Next? If you are interested in completing Jquery tutorial, your next topic will be learning about: Jquery find method.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.