Page Content

Tutorials

What Are The Filter Methods In jQuery With Code Example

Filter Methods

Filter Methods
Filter Methods

You may precisely adjust sets of chosen HTML components on a web page with the help of jQuery’s robust algorithms, such as filters and filter methods. These features are essential to jQuery’s objective of making HTML document manipulation and traversal simpler for quick web development.

Filters vs. Filter Methods

It’s critical to differentiate between filter methods and filters (also known as custom selectors):

Filters (Custom Selectors): Custom selectors, often known as filters, are unique additions to regular CSS selectors that let you choose items according to more precise standards that aren’t possible with just CSS. Usually, they are included in the first selector string that is supplied to the jQuery() method (or its alias $()). :eq(), :not(), :first, :last, :odd, :even, :contains(), and :hidden/:visible are a few examples.

Filter Methods: These are methods used after jQuery() has been used to pick a collection of elements. To further refine, or filter, the set of items, they are called on the generated jQuery object. When working with items that need JavaScript logic for filtering, it might occasionally be more effective to use filter methods after a first, more comprehensive selection rather than a very complicated initial selector.

Filter Methods in jQuery

.eq(index) Method: At a zero-based index, the.eq(index) technique limits the set of matched entries to one. If your collection contains ten elements,.eq(0) takes the first,.eq(1) the second, etc. Index, the desired element’s zero-based placement in the current set, is an integer argument. From the end of the set, count with a negative index like -1.

It’s especially helpful when you need to work on a single component of a bigger collection. For instance, you would first choose every paragraph before applying if you had several and just wanted to focus on the third one.Equation (2).

The.eq() technique can be used after a broad first selection (e.g., $(‘p’)), but the :eq(index) selector can also produce a comparable result as part of the original selection.Because it enables jQuery to use faster native DOM lookups first, eq(2)) can occasionally provide greater performance, particularly in contemporary browsers.

.not(selector/function) Method: Elements that do not fit a given selector or for which a callback function returns true are eliminated from the collection of matched elements using the.not() method. In essence, it lets you take some items out of your current selection. This technique is perfect for reducing a selection by specifically removing items that satisfy particular requirements. For example, you could use.not(‘.excluded-class’) to select all list items except those with a particular class.

  • All elements in the current set that also match the specified selector will be eliminated if one is supplied.
  • Every element in the set receives a single call to the function, if one is supplied. That element is removed from the result set if the function returns true. This is effective when using intricate logical exclusions.

.first() Method: The jQuery.first() DOM traversal technique returns a jQuery object with only the first element from a previously matched set. It filters the selected elements to the first one. .first() selects the first item in a list. This function selects the last element in a result set, like.last(). After an initial selector, such as $(‘li’).first() instead of $(‘li:first’), jQuery can use the browser’s native DOM selector engine for the initial broad selection and then apply the.first() method as a simpler array operation, which can improve performance.

Regardless of the collection’s exact index, this method is simple and helpful when you only need to work with the first piece. For instance, you would choose every paragraph on a page and then apply.first() to that selection if you wanted to style just the first paragraph.

.last() Method: The jQuery.last() DOM traversal filtering function reduces the set of matched components to the last one. This method is handy when you have multiple items of the same type and need to interact with the final instance in the selection. If you have a list of photos and want to operate solely on the last one, use $(‘img’).last(). Like the last selector (e.g., $(‘img:last’)), it chooses the final matching element in a result set.

.last() is a method applied to a jQuery object after an initial selection, while last is a pseudo-class selector used directly in the $( ) factory function. The following filtering techniques allow exact selection within a collection of elements: first(), eq(index), not(selector), slice(start, end), filter(selector), and map(callback).

.filter(selector/function) Method: Elements that do not match the designated selector or elements for which a callback function returns false are eliminated from the list of matched elements using the.filter() method. Essentially, only the components that meet the specified requirements are retained.

The goal of this strong filter method is to reduce a large selection to a highly specific subset depending on any condition that can be expressed using JavaScript logic or a selector. For instance, you can use a filter function to check the hostname property if you wish to choose links that lead to external domains.

Code Example: Applying Filter Methods

Examine a straightforward HTML structure that has an unordered list of elements. Using the filter methods in jQuery, we will apply various styles to particular list items:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Fruit Colors Example</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    li {
      padding: 6px;
      border: 1px solid #ccc;
      margin-bottom: 4px;
    }
    .apple { background-color:  orange; }    
    .banana { background-color: Yellow; }   
    .grapes { background-color: green; }   
  </style>
</head>
<body>
<h3>Fruits List</h3>
<ul id="fruitList">
  <li class="red">Apple</li>
  <li class="yellow">Banana</li>
  <li class="green">Grapes</li>
</ul>
<script>
  $(document).ready(function() {
    // Apply unique colors based on fruit text
    $('#fruitList li').filter(function() {
      return $(this).text().includes("Apple");
    }).addClass('apple');
    $('#fruitList li').filter(function() {
      return $(this).text().includes("Banana");
    }).addClass('banana');
    $('#fruitList li').filter(function() {
      return $(this).text().includes("Grapes");
    }).addClass('grapes');
  });
</script>
</body>
</html>

Output:

Fruits List
Apple

Banana

Grapes

Conclusion

The jQuery filter methods.eq(),.not(),.first(),.last(), and.filter() are crucial for selecting and manipulating with certain elements in a set of matched elements. These methods improve DOM manipulation precision and efficiency. This approach lets developers target elements at specified indexes by selecting a single element depending on its position. .not(selector/function) is ideal for excluding unwanted items because it removes elements that match a criterion. First() and last() are simple ways to access the first and final members in a set, which is important for boundary-related actions.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index