jQuery filter()Method

jQuery 遍历方法jQuery Traversing Methods

Examples

Return all <p> elements with class name "intro":

$("p").filter(".intro")

Try it Yourself »

Definition and Usage

The filter() method returns elements that match certain criteria.

This method lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match are returned.

This method is often used to narrow down the range of elements searched within the selected set of elements.

Tip:The filter() method is the opposite ofnot()the method.


Syntax

$(selector).filter(criteria,function(index))

Parameters Description
criteria Optional. Specifies a selector expression, a jQuery object, or one or more elements to return from the selected set of elements.

Tip:To specify multiple criteria, separate them with commas.
function(index) Optional. Specifies a function to run for each element in the set. If it returns true, the element is kept; otherwise, the element is removed.
  • index- The index position of the element in the set.
Note: thisis the current DOM element.

实例

More Examples

Return all even-numbered <p> elements
Use the :even selector and filter() to return all even-numbered <p> elements.

Multiple Criteria
How to return all <p> elements with class "intro" and id "outro".

Using a jQuery Object
How to return all <p> elements with class "intro" inside a <div> element using a jQuery object.

DOM
How to return a <p> element with id "intro" using a DOM element.

Using a Function
How to use a function to select all <p> elements that contain two <span> elements.


jQuery 遍历方法jQuery Traversing Methods

Other Extensions