jQuery Tutorial

jQuery Traversing Filtering: first(), last(), eq(), filter(), not()

Table of Contents

  • Understanding Traversing Filtering in jQuery
  • jQuery first() Method
  • jQuery last() Method
  • jQuery eq() method
  • jQuery filter() Method
  • jQuery not() Method

Understanding Traversing Filtering in jQuery

The first(), last(), and eq() filtering methods allow you to select a specific element based on its position in a group of elements.

Other filtering methods, such as filter() and not(), let you select elements that meet or don't meet a set of criteria.

jQuery first() Method

In the specified set of elements, the first() method returns the first element. 

The first

element is selected in the following example:

Example of first method in jQuery

$(document).ready(function(){
  $("div").first();
});

jQuery last() Method

The last() method returns the specified elements' previous elements.

The last

element is selected in the following example:

Example of last method in jQuery

$(document).ready(function(){
  $("div").last();
});

jQuery eq() method

The eq() method returns an element with the selected elements' index number.

Because the index numbers begin at 0, the first element will have the index number 0 rather than 1. The second

element (index number 1) is selected in the following example:

Example of eq method in jQuery

$(document).ready(function(){
  $("p").eq(1);
});

jQuery filter() Method

You can use the filter() method to specify criteria. Elements that do not meet the requirements are removed from the list, while those that do are returned.

All

elements with the class "intro" are returned in the following example:

Example of filter method in jQuery

$(document).ready(function(){
  $("p").filter(".intro");
});

jQuery not() Method

The not() method returns all elements that do not match the criteria.

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

In this example, it will return all

elements with the class name "intro" but no class name:

Example of not method in jQuery

$(document).ready(function(){
  $("p").not(".intro");
});
Did you find this article helpful?