In jQuery, filtering allows you to refine your selection of elements by narrowing down the set of matched elements based on certain criteria.
1. Common jQuery Filtering Methods
Here are the most commonly used filtering methods:
Method | Description |
---|---|
.filter(selector) |
Filters elements based on a selector, function, or element. |
.not(selector) |
Excludes elements that match the selector. |
.is(selector) |
Checks if any element in the set matches the selector (returns true/false ). |
.has(selector) |
Filters elements that contain the specified descendant. |
.eq(index) |
Selects the element at the specified index (0-based). |
.first() |
Selects the first element in the set. |
.last() |
Selects the last element in the set. |
.slice(start, end) |
Selects a subset of elements based on start and end indices. |
2. Examples
HTML Structure:
<ul id="list"> <li>Item 1</li> <li class="active">Item 2</li> <li>Item 3</li> <li class="active">Item 4</li> <li>Item 5</li> </ul>
jQuery Filtering Examples:
- Filter Elements by Class:
- Exclude Elements:
- Check if an Element Matches:
- Filter by Descendant:
- Select the First Element:
- Select the Last Element:
- Select by Index:
- Select a Range of Elements: