jQuery Filtering

jQuery Traversing - Filtering

When selecting an element from a large HTML document, you might get a massive array of results.

jQuery provides several filtering methods to narrow down those results to an exact element.

This is incredibly helpful for finding items based on their specific position or properties.


Common Filtering Methods

The three most basic filtering methods are:

Additionally, filter() and not() allow you to match elements against custom criteria.


The first() and last() Methods

The first() method returns the first element of the specified elements.

The last() method returns the last element of the specified elements.

First and Last Example:

$(document).ready(function(){
  // Finds the very first paragraph in the entire document
  $("div p").first().css("background-color", "yellow");
  // Finds the very last paragraph in the document
  $("div p").last().css("background-color", "lightblue");
});

The eq() Method

The eq() method returns an element with a specific index number from the selected elements.

The index numbers start at 0, meaning the very first element has an index number of 0.

The eq() Example:

$(document).ready(function(){
  // Selects the second paragraph (index 1)
  $("p").eq(1).css("background-color", "yellow");
});

The filter() Method

The filter() method lets you specify a criterion.

Elements that do not match the criterion are removed from the selection, and those that match will be returned.

The filter() Example:

$(document).ready(function(){
  // Out of all paragraphs, return only those with class="intro"
  $("p").filter(".intro").css("background-color", "yellow");
});

The not() Method

The not() method is the exact opposite of filter().

It returns all elements that do NOT match the criteria.

The not() Example:

$(document).ready(function(){
  // Out of all paragraphs, return only those that DO NOT have class="intro"
  $("p").not(".intro").css("background-color", "yellow");
});

Exercise 1 of 1

?

If you want to select the third element in a list of results, what eq() value would you use?