jQuery Traversal - Filtering
Narrowing Down the Scope of Search Elements
The three most basic filtering methods are: first(), last(), and eq(), which allow you to select a specific element based on its position within a set of elements.
Other filtering methods, such as filter() and not(), allow you to select elements that either match or do not match a specified criterion.
jQuery first() Method
The first() method returns the first element of the selected elements.
The following example selects the first <p> element inside the first <div> element:
Example
$(document).ready(function(){
$("div p").first();
});
jQuery last() Method
The last() method returns the last element of the selected elements.
The following example selects the last <p> element inside the last <div> element:
Example
$(document).ready(function(){
$("div p").last();
});
jQuery eq() Method
The eq() method returns the element with the specified index number from the selected elements.
The index starts at 0, so the first element's index is 0 rather than 1. The following example selects the second <p> element (index number 1):
Example
$(document).ready(function(){
$("p").eq(1);
});
jQuery filter() Method
The filter() method allows you to specify a criterion. Elements that do not match this criterion are removed from the set, and matching elements are returned.
The following example returns all <p> elements with the class name "url":
Example
$(document).ready(function(){
$("p").filter(".url");
});
jQuery not() Method
The not() method returns all elements that do not match the criterion.
The following example returns all <p> elements that do not have the class name "url":
Example
$(document).ready(function(){
$("p").not(".url");
});