jQuery Traversing: Filtering
After selecting or traversing, you often have more elements than you need. Filtering methods narrow a set down — by position, by selector, by a custom test, or by what the elements contain.
Filtering by position
| Method | Keeps |
|---|---|
.first() |
The first element |
.last() |
The last element |
.eq(n) |
The element at index n (0-based); negative counts from the end: .eq(-1) is the last |
.even() / .odd() |
Elements at even / odd 0-based indexes (jQuery 3.5+) |
.slice(start, end?) |
A range, like Array.prototype.slice |
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; font-size: 13px; }
ol li { padding: 2px 6px; }
.hl { background: #fff176; }
</style>
</head>
<body>
<ol id="list">
<li>Index 0</li><li>Index 1</li><li>Index 2</li><li>Index 3</li><li>Index 4</li><li>Index 5</li>
</ol>
<button data-code='first()'>first()</button>
<button data-code='last()'>last()</button>
<button data-code='eq(2)'>eq(2)</button>
<button data-code='eq(-2)'>eq(-2)</button>
<button data-code='even()'>even()</button>
<button data-code='odd()'>odd()</button>
<button data-code='slice(1, 4)'>slice(1, 4)</button>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
const $items = $("#list li");
const run = {
"first()": $s => $s.first(),
"last()": $s => $s.last(),
"eq(2)": $s => $s.eq(2),
"eq(-2)": $s => $s.eq(-2),
"even()": $s => $s.even(),
"odd()": $s => $s.odd(),
"slice(1, 4)": $s => $s.slice(1, 4)
};
$("button").on("click", function () {
const code = $(this).data("code");
$items.removeClass("hl");
const $r = run[code]($items).addClass("hl");
console.log(code, "→ indexes", $r.map(function () { return $items.index(this); }).get());
});
</script>
</body>
</html>Filtering by selector or test
| Method | Keeps |
|---|---|
.filter(selector) |
Elements matching the selector |
.filter(function (i, el) {…}) |
Elements for which the function returns true |
.not(selector or fn) |
Elements that do not match (the opposite of filter) |
.has(selector) |
Elements that contain a matching descendant |
.is(selector) |
Returns true/false — does any element match? (not a set) |
A live search filter
.filter() with a function is the tool for conditions that selectors cannot express — like "the text contains what the user typed":
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; font-size: 14px; }
#people li { padding: 3px 0; }
#people li.vip::after { content: " ⭐"; }
</style>
</head>
<body>
<input id="q" placeholder="Search names…"> <label><input type="checkbox" id="vip"> VIP only</label>
<ul id="people">
<li>Ana Lima</li>
<li class="vip">Ben Okafor</li>
<li>Chloe Martin</li>
<li class="vip">Daniel Kim</li>
<li>Elena Rossi</li>
<li class="vip">Farid Haddad</li>
</ul>
<p id="count"></p>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
const $people = $("#people li");
function apply() {
const q = $("#q").val().toLowerCase();
const vipOnly = $("#vip").is(":checked");
const $matches = $people.filter(function () {
return $(this).text().toLowerCase().includes(q);
}).filter(vipOnly ? ".vip" : "*");
$people.not($matches).hide();
$matches.show();
$("#count").text($matches.length + " of " + $people.length + " shown");
console.log("query:", JSON.stringify(q), "vip:", vipOnly, "→", $matches.length);
}
$("#q").on("input", apply);
$("#vip").on("change", apply);
apply();
</script>
</body>
</html>Note how .filter() calls can be chained: first by text, then by class. .not($matches) gives the complement — every person that did not match.
has() and is()
.has() filters by content; .is() answers a yes/no question:
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; font-size: 14px; }
.post { border: 1px solid #ccc; border-radius: 6px; padding: 6px 10px; margin: 6px 0; width: 280px; }
.post.with-img { border-color: #0769ad; background: #eef5fb; }
.icon { display: inline-block; width: 14px; height: 14px; background: #e67e22; border-radius: 3px; }
</style>
</head>
<body>
<div class="post"><b>Post A</b> — text only</div>
<div class="post"><b>Post B</b> — has an icon <span class="icon"></span></div>
<div class="post"><b>Post C</b> — text only</div>
<div class="post"><b>Post D</b> — has an icon <span class="icon"></span></div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
const $posts = $(".post");
$posts.has(".icon").addClass("with-img");
console.log("posts with icons:", $posts.has(".icon").length);
console.log("is any post .with-img?", $posts.is(".with-img"));
console.log("is the first one?", $posts.first().is(".with-img"));
$posts.on("click", function () {
const pos = $posts.index(this);
console.log("clicked post", pos, "| has icon:", $(this).is(":has(.icon)"));
});
</script>
</body>
</html>Choosing the right tool
| Question | Use |
|---|---|
| "Give me the 3rd one" | .eq(2) |
| "Only the ones with class X" | .filter(".x") |
| "All except this one" | .not(this) |
| "The ones whose value/text meets a condition" | .filter(function) |
| "The ones containing a Y" | .has("y") |
| "Is this element a Z?" | .is(".z") (returns a boolean) |
Tip:
.filter()and.not()also accept a jQuery object or DOM element, e.g.$items.not($selected).
Test yourself
What does $("li").eq(-1) return?
- Nothing — negative indexes are invalid
- The first
li - The last
li - All but the last
li
Which method returns a boolean instead of a jQuery object?
.filter().not().has().is()
How do you keep only list items whose text is longer than 10 characters?
$("li").filter(":length(10)")$("li").filter(function () { return $(this).text().length > 10; })$("li").has(10)$("li").is("> 10")