English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
With jQuery, we can easily filter out various elements from a list of DOM elements.
In this chapter, we will explain how to narrow down the search range for elements in the DOM tree.
We have the following jQuery methods for selecting elements based on their position in a set of elements:
Below, we will show you how to use each method.
jQuery first()The method returns the first element of the selected element.
The following example highlights the first paragraph:
$ (document).ready(function() { $("p").first().css("background", "coral"); });Test It Out‹/›
jQuery last()The method returns the last element of the selected element.
The following example highlights the last paragraph:
$ (document).ready(function() { $("p").last().css("background", "coral"); });Test It Out‹/›
jQuery eq()The method returns the element with the specific index number of the selected element.
The index number always starts from 0, so the first number will have an index of 0 (not1).
The following example selects the third paragraph (index number2):
$("button").click(function(){ $("p").eq(2).css("background-color", "red"); });Test It Out‹/›
jQuery filter()The method returns elements that match a specific condition.
This method filters out all elements that do not meet the selected conditions and returns those that match.
The following example returns all paragraphs with the class name 'demo':
$ (document).ready(function() { $("p").filter(".demo").css("background", "coral"); });Test It Out‹/›
The following example returns all even list items:
$ (document).ready(function() { $("li").filter(":even").css("background", "coral"); });Test It Out‹/›
jQuery not()method returns elements that do not match a specific condition.
This method is similar to thefilter()The opposite method.
The following example returns all paragraphs that do not have the class name 'demo':
$ (document).ready(function() { $("p").not(".demo").css("background", "coral"); });Test It Out‹/›
jQuery has()This method returns all elements that match the specified selector, containing one or more elements.
The following example returns all paragraphs that contain a <span> element:
$ (document).ready(function() { $("p").has("span").css("background"-color", "coral"); });Test It Out‹/›
jQuery is()This method checks if one of the selected elements matches the given parameter.
If at least one of these elements matches the given parameter, this method will return true, otherwise it will return false.
The following example checks if the parent of <p> is a <div> element:
$ (document).ready(function() { $("p").parent().is("div"); });Test It Out‹/›
For a complete reference of traversal methods, please visit ourjQuery Traversal Reference.