jQuery Filtering
Filtering is how you take a set of matched elements and narrow it down to just the ones you actually want. Maybe you selected every list item on the page but you only need the first one, the last one, the third one, or the ones that do not have a certain class. jQuery gives you a focused group of methods for this: first(), last(), eq(), filter(), and not(). Together they let you slice a collection with precision.
Narrowing Down a Selection
A jQuery selector often matches more elements than you need. Filtering methods let you reduce that group down to a smaller, more specific set. Some methods pick by position, like first() and last(). Others pick by matching a condition, like filter() and not(). The result is always a new jQuery object containing only the elements that survived the filter.
- first() - keeps only the first element of the set.
- last() - keeps only the last element of the set.
- eq(index) - keeps the element at a specific zero-based position.
- filter(selector) - keeps only elements that match the given selector.
- not(selector) - keeps only elements that do NOT match the given selector.
Filtering by Position
first(), last(), and eq() choose elements based on where they sit in the matched set. Remember that eq() counts from zero, so eq(0) is the first element and eq(2) is the third. You can pass a negative number to eq() to count backward from the end, where eq(-1) is the last element.
Picking by position
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<ul>
<li>Item one</li>
<li>Item two</li>
<li>Item three</li>
<li>Item four</li>
</ul>
<script>
$(document).ready(function() {
// Style the first and last list items
$("li").first().css("font-weight", "bold");
$("li").last().css("color", "crimson");
// Style the third list item (index 2)
$("li").eq(2).css("background", "#f5f5f5");
});
</script>
</body>
</html>Filtering by Match with filter() and not()
filter() and not() are opposites. filter() keeps the elements that match a selector, and not() throws those elements away and keeps the rest. Both are useful when a plain selector cannot express what you want, for example selecting all paragraphs except the ones tagged as intro text.
Using filter() and not()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p class="intro">This is the introductory paragraph.</p>
<p class="note">This is a note paragraph.</p>
<p>This is a plain paragraph.</p>
<script>
$(document).ready(function() {
// Keep only the paragraphs that also have class "note"
$("p").filter(".note").css("border-left", "3px solid orange");
// Keep every paragraph EXCEPT the intro one
$("p").not(".intro").css("color", "#333");
});
</script>
</body>
</html>Exercise: jQuery Filtering
What does .first() do when called on a jQuery collection?