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.
The three most basic filtering methods are:
first()last()eq()Additionally, filter() and not() allow you to match elements against custom criteria.
The first() method returns the first element of the specified elements.
The last() method returns the last element of the specified elements.
$(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 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.
$(document).ready(function(){
// Selects the second paragraph (index 1)
$("p").eq(1).css("background-color", "yellow");
});
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.
$(document).ready(function(){
// Out of all paragraphs, return only those with class="intro"
$("p").filter(".intro").css("background-color", "yellow");
});
The not() method is the exact opposite of filter().
It returns all elements that do NOT match the criteria.
$(document).ready(function(){
// Out of all paragraphs, return only those that DO NOT have class="intro"
$("p").not(".intro").css("background-color", "yellow");
});
If you want to select the third element in a list of results, what eq() value would you use?