jQuery Filtering Methods
jQuery offers several filtering methods to help you narrow down a group of selected elements. These methods let you select elements based on their position or whether they match specific criteria.
Basic Filtering Methods
- first() – Selects the first element in the matched set.
- last() – Selects the last element in the matched set.
- eq() – Selects an element at a specific index.
Advanced Filtering Methods
- filter() – Keeps only elements that match a given selector or condition.
- not() – Removes elements that match a given selector or condition.
jQuery first() Method
The first() method returns only the first element from a group of matched elements.
Example
The following code selects the first <div> element on the page:
$(document).ready(function(){
$("div").first();
});
This is useful when you want to perform an action on just the first occurrence of an element type.
jQuery last() Method
The last() method is used to select the last element from a group of matched elements.
Example
The following code selects the last <div> element on the page:
$(document).ready(function(){
$("div").last();
});
This method is helpful when you want to target the final occurrence of an element within a collection for styling or manipulation.
jQuery eq() Method
The eq() method is used to select an element at a specific index from a group of matched elements.
Indexing starts at 0, so the first element has index 0, the second has index 1, and so on.
Example
The following example selects the second <p> element (which has an index of 1):
$(document).ready(function(){
$("p").eq(1);
});
This method is useful when you need to target a single element from a list based on its position.
jQuery filter() Method
The filter() method allows you to refine a selection by specifying a condition or selector. Only the elements that match the given criteria are kept; the rest are removed from the selection.
Example
The following code selects all <p> elements that have the class "intro":
$(document).ready(function(){
$("p").filter(".intro");
});
This method is useful when you want to narrow down a group of elements to only those that meet certain requirements.
jQuery not() Method
The not() method is used to exclude elements that match a specific selector or condition from a group of matched elements.
Example
The following code selects all <p> elements except those with the class "intro":
$(document).ready(function(){
$("p").not(".intro");
});
This is helpful when you want to apply actions or styles to all elements in a group except certain ones.