jQuery Traversing: Filtering

Sometimes a selector finds more elements than you need. The filtering methods help to narrow the selection.

<ul id="list">
  <li class="item">Apple</li>
  <li class="item hot">Banana</li>
  <li class="item">Cherry</li>
  <li class="item hot">Date</li>
  <li class="item">Elderberry</li>
</ul>
MethodMeaning
.first() / .last()The first or the last element
.eq(n)The element at the index n (starts from 0, negative counts from the end)
.filter(sel)Keeps only the elements which match
.not(sel)Removes the elements which match
.has(sel)Keeps the elements which have a matching descendant
.is(sel)Returns true if at least one element matches
.slice(a, b)A part of the selection, from index a up to (not including) b
var text = function ($els) { return $els.map(function () { return $(this).text(); }).get().join(', '); };

console.log('first:  ' + text($('.item').first()));
console.log('last:   ' + text($('.item').last()));
console.log('eq(2):  ' + text($('.item').eq(2)));
console.log('eq(-1): ' + text($('.item').eq(-1)));
console.log('filter: ' + text($('.item').filter('.hot')));
console.log('not:    ' + text($('.item').not('.hot')));
console.log('slice:  ' + text($('.item').slice(1, 3)));
console.log('is:     ' + $('.item').first().is('.hot'));
Console output

first: Apple
last: Elderberry
eq(2): Cherry
eq(-1): Elderberry
filter: Banana, Date
not: Apple, Cherry, Elderberry
slice: Banana, Cherry
is: false

filter() with a function

You can give a function that returns true for the elements to keep.

var $long = $('.item').filter(function (index) {
  return $(this).text().length > 5;
});
console.log($long.length);
console.log($long.eq(0).text());
Console output

3
Banana

has()

<div class="card"><p>Text only</p></div>
<div class="card"><p>With <b>bold</b></p></div>
console.log($('.card').has('b').length);
console.log($('.card').has('b').text());
Console output

1
With bold

add() to join selections

<h2>Title</h2>
<p>Text</p>
<span>Extra</span>
var $all = $('h2').add('p').add('span');
console.log($all.length);
Console output

3

Filtering after another traversal

You can use the filters at any point in a chain, for example $('li').filter('.hot').last().addClass('top').

Note: .is() is the best method for a condition in an if. For example: if ($(this).is(':checked')) { ... }. Next: jQuery each() and map().

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write jQuery code to count the items of a list
Write jQuery code to find the total of a table column
Write jQuery code to add alternate row colors to a table
Interview Questions & Answers
What are jQuery selectors?
What is the difference between find() and children() in jQuery?
What is the difference between parent(), parents() and closest() in jQuery?
How do you check if an element exists in jQuery?
What is the difference between this and $(this) in jQuery?
What is the use of end() in jQuery?