0PricingLogin
jQuery Academy · Lesson

Advanced Filtering with .filter()

Explore the full power of the .filter() method, using functions to apply custom logic and select elements based on dynamic properties or relationships.

Refine Selections with .filter()

The .filter() method in jQuery is a powerful way to narrow down an existing set of selected elements. It helps you keep only the elements that match specific criteria.

Think of it as a second layer of selection, applied after your initial selection, to achieve greater precision.

Basic Filter with Selectors

The simplest way to use .filter() is by providing a CSS selector string. This works just like a standard selector, but it only applies to the elements already in your current jQuery set.

Let's select all divs with class .item, then filter them to keep only those that also have the class .active.

<!DOCTYPE html>
<html>
<head>
<title>Filter by Selector</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
  <div class="item">Item 1</div>
  <div class="item active">Item 2</div>
  <div class="item">Item 3</div>
  <div class="item active">Item 4</div>

  <script>
    $(document).ready(function(){
      // Select all divs with class 'item'
      var allItems = $('div.item');
      // Then filter to keep only those with class 'active'
      var activeItems = allItems.filter('.active');
      activeItems.css('color', 'blue');
    });
  </script>
</body>
</html>

All lessons in this course

  1. Building Custom Pseudo-Selectors
  2. Advanced Filtering with .filter()
  3. Excluding Elements with .not()
← Back to jQuery Academy