Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 56 ยท Selecting Elements

Filtering Methods

Narrow a jQuery selection with .filter(), .not(), .has(), .is(), .first(), .last(), .eq() and .slice(), and transform it with .map() and .each().

A selector gives you a set of elements, but the set is often too big. You want only the rows that are overdue, the inputs that are empty, the items except the one the user clicked. jQuery solves this with filtering methods: you select broadly, then reduce the collection step by step. Each method returns a new jQuery object, so the calls chain naturally.

Filtering with methods has two advantages over jQuery's special selectors such as :first or :visible, which you met in filtering selectors. The methods are faster (the CSS part of the selection can run natively, see selector performance), and they accept functions, so any rule you can write in JavaScript can decide which elements stay.

Keep, drop, or test

filter Keep elements that match.
not Drop elements that match.
has Keep elements that contain a match.
is Ask a yes or no question.
1 / 2

.filter(): keep what matches

.filter() reduces the set to elements that match a selector, a DOM element, another jQuery object, or a function.

JavaScript
$("li").filter(".done");          // only li elements with class done
$("li").filter(":even");          // jQuery extension works here too
$("li").filter(":not(.done)");    // CSS negation

With a function, jQuery calls it once per element, with this set to the element and the index as the first argument. Return a truthy value to keep the element.

JavaScript
$("li").filter(function (index) {
  return $(this).text().length > 8;   // keep long labels
});

.not(): drop what matches

.not() is the opposite of .filter(). It accepts the same kinds of arguments and removes the matches.

JavaScript
$("li").not(".done");                       // every item that is not done
$("li").not(this);                          // all items except the clicked one
$("li").not(function () { return $(this).data("locked"); });

A very common use is "everyone except the element I am handling", for example closing all other panels when one opens.

.has(): keep elements that contain something

.has() keeps the elements that have at least one descendant matching the selector. The element itself does not have to match.

JavaScript
$("li").has("ul");        // list items that contain a nested list
$("tr").has("input:checked");  // rows with a checked box inside

Do not confuse it with .find(): .has() returns the same elements it started with (just fewer of them), while .find() returns the descendants.

.is(): a yes or no question

.is() does not return a jQuery object. It returns a boolean: true if at least one element in the set matches. It takes the same arguments as .filter().

JavaScript
if ($(this).is(":checked")) { /* ... */ }
if ($("#menu").is(":visible")) { /* ... */ }
if ($(event.target).is("a.external")) { /* ... */ }

Use .is() in conditions, and .filter() when you want the elements themselves.

The next example puts the four methods side by side on a to-do style list. Each button applies one rule and highlights the result.

filter, not, has and is in action

Picking by position

Sometimes you do not care what an element is, only where it sits in the set.

Method Result
.first() the first element
.last() the last element
.eq(n) the element at index n; a negative number counts from the end
.slice(start, end) elements from start up to (not including) end
JavaScript
$("li").first();        // same as $("li:first"), but faster
$("li").eq(2);          // third item (indexes start at 0)
$("li").eq(-1);         // last item
$("li").slice(1, 4);    // second, third and fourth
$("li").slice(-2);      // last two

Each of these returns a jQuery object, even if it holds a single element. To get the raw DOM node, use [0] or .get(0), as described in the jQuery object.

.map() and .each() on a set

Two more methods are used right after filtering. They get their own deeper treatment in working with collections, but here is the short version.

  • .each(function (index, element) { ... }) runs code for every element. It returns the original set, so chaining continues. Return false to stop early.
  • .map(function (index, element) { ... }) builds a new jQuery object from the values you return. Call .get() on the result to turn it into a plain array.
JavaScript
const names = $("li.done")
  .map(function () { return $(this).text(); })
  .get();            // ["Buy milk", "Call Sam", ...]

If a .map() callback returns null or undefined, that item is skipped, which makes .map() handy for filtering and transforming in one step.

Position methods and map()

Choosing the right method

A quick way to remember: ask what you want back.

  • A smaller set of the same elements: .filter(), .not(), .has(), .first(), .last(), .eq(), .slice().
  • A yes or no: .is().
  • Different values or elements built from the set: .map().
  • Just run some code: .each().

Prefer a descriptive selector or a class when you can (for example .overdue), and reach for a function filter only when the rule needs real logic.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does $('li').not('.done') return?

    .not() removes the matches and returns a jQuery object with the rest.
  2. 2. How does .has('ul') differ from .find('ul')?

    .has() filters the current set by descendants. .find() moves to the descendants themselves.
  3. 3. Which call tells you whether the clicked element is a link?

    .is() returns true or false, which is what an if statement needs. .filter('a') returns an object that is always truthy, even when empty.
  4. 4. What does $('li').slice(1, 3) select?

    Like Array.prototype.slice, the end index is not included, and counting starts at 0.
  5. 5. In a .map() callback, what happens if you return null?

    jQuery's .map() drops null and undefined results, so you can filter and transform in one pass. The DOM is untouched.

Summary

  • Select broadly with a CSS selector, then narrow with methods; each returns a new jQuery object.
  • .filter() keeps matches, .not() removes them, .has() keeps elements that contain a match.
  • .is() returns a boolean, so use it in if conditions; an empty jQuery object is still truthy.
  • .first(), .last(), .eq(n) and .slice(a, b) pick by position; negative indexes count from the end.
  • Function arguments to .filter() and .not() get this and the index, and decide with any JavaScript rule.
  • .map() builds a new set (skipping null); .each() runs code and returns the original set.

Next: Traversing Up the Tree starts the Traversing chapter by moving from an element to its parents and ancestors.