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.
Advanced Filtering with .filter() is a free jQuery Academy lesson on CoddyKit — lesson 2 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the jQuery Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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>Custom Logic with a Function
The true strength of .filter() comes when you pass a function as an argument. This lets you apply highly custom and dynamic logic to each element in your selection.
- The function runs for each element in the current jQuery set.
- It receives two arguments:
index(the element's position in the set) andelement(the raw DOM element). - Return
trueto keep the element, andfalseto remove it from the filtered set.
Filtering by Index Position
You can use the index argument in your filter function to select elements based on their position within the current jQuery set. This is useful for tasks like selecting every second item or specific ranges.
Let's select every second list item (those at even indices, starting from 0) and highlight them.
<!DOCTYPE html>
<html>
<head>
<title>Filter by Index</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
<ul>
<li>Item 0</li>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
<script>
$(document).ready(function(){
$('li').filter(function(index) {
// Keep items at even indices (0, 2, 4...)
return index % 2 === 0;
}).css('background-color', 'lightgreen');
});
</script>
</body>
</html>Based on Attributes and Properties
The element argument (or $(this) inside the function) allows you to inspect each DOM element's properties, attributes, or text content. This enables highly specific filtering.
Here, we'll find all list items that contain the word "Important" in their text and make them bold.
<!DOCTYPE html>
<html>
<head>
<title>Filter by Property</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
<ul>
<li>Task 1</li>
<li>Important Task 2</li>
<li>Task 3</li>
<li>Another Important Task 4</li>
</ul>
<script>
$(document).ready(function(){
$('li').filter(function() {
// Check if the text content includes "Important"
return $(this).text().includes('Important');
}).css('font-weight', 'bold');
});
</script>
</body>
</html>Dynamic Filtering with Data
HTML5 data attributes (e.g., data-status="active") are perfect for storing extra, application-specific information directly on elements. You can use .filter() to select elements based on these custom data values.
Let's highlight list items that are marked as 'complete' using their data-status attribute.
<!DOCTYPE html>
<html>
<head>
<title>Filter by Data</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
<ul>
<li data-status="pending">Task A</li>
<li data-status="complete">Task B</li>
<li data-status="pending">Task C</li>
<li data-status="complete">Task D</li>
</ul>
<script>
$(document).ready(function(){
$('li').filter(function() {
// Check the 'data-status' attribute
return $(this).data('status') === 'complete';
}).css('text-decoration', 'line-through');
});
</script>
</body>
</html>Filtering by Child or Parent
Your filter function can also inspect the relationships between elements. For example, you might want to select parent elements that contain a specific child, or vice versa.
Here, we'll find list items that contain an <img> tag within them and add a border.
<!DOCTYPE html>
<html>
<head>
<title>Filter by Relationship</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
<ul>
<li>Text only</li>
<li>Item with <img src="https://placehold.co/16x16" alt="icon"></li>
<li>Another text item</li>
<li>Item with another <img src="https://placehold.co/16x16" alt="image"></li>
</ul>
<script>
$(document).ready(function(){
$('li').filter(function() {
// Check if the current <li> contains an <img>
return $(this).find('img').length > 0;
}).css('border', '2px solid orange');
});
</script>
</body>
</html>Complex Filters with Logic
Inside your filter function, you can combine multiple conditions using standard JavaScript logical operators like && (AND) and || (OR).
This allows for very precise selections based on several criteria at once, making your filtering extremely powerful:
- Is it visible? AND does it have a specific class?
- Does it contain text 'X'? OR does it have data attribute 'Y'?
Real-World Dynamic Filtering
Let's put together what we've learned. Imagine filtering a list of products based on multiple criteria. Your filter function can check several conditions dynamically.
This example highlights products that are both visible AND belong to the 'electronics' category, using combined logic within the filter function.
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Filtering</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<style>
.hidden { display: none; }
</style>
</head>
<body>
<div class="product" data-category="electronics">Laptop</div>
<div class="product hidden" data-category="books">Novel</div>
<div class="product" data-category="electronics">Mouse</div>
<div class="product" data-category="books">Textbook</div>
<script>
$(document).ready(function(){
$('div.product').filter(function() {
// Filter products that are visible AND in 'electronics' category
var isVisible = $(this).is(':visible');
var isElectronics = $(this).data('category') === 'electronics';
return isVisible && isElectronics;
}).css('background-color', 'lightblue');
});
</script>
</body>
</html>Filter Challenge
Given the HTML <li class="item special" data-value="10">...</li>, which .filter() function correctly selects only <li> elements that have the class .special AND a data-value greater than 5?
Recap: Dynamic Filtering Power
You've now mastered the advanced uses of jQuery's .filter() method!
- It refines existing selections, providing precise control.
- Using a function unlocks dynamic and complex filtering logic.
- You can inspect indices, element properties, data attributes, and relationships.
- Combine multiple conditions with
&&(AND) and||(OR) for highly specific criteria.
This powerful method allows you to create incredibly responsive and data-driven user interfaces.
Frequently asked questions
Is the “Advanced Filtering with .filter()” lesson free?
Yes — the full text of “Advanced Filtering with .filter()” is free to read here on the web, and the jQuery Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the jQuery Academy course, upgrade to CoddyKit PRO.
What will I learn in “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. You practise jQuery Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start jQuery Academy?
No prior experience is required. jQuery Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 3, so you can start here or from the beginning and move at your own pace.
How long does the “Advanced Filtering with .filter()” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this jQuery Academy lesson?
Yes. Every jQuery Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Building Custom Pseudo-Selectors
- Advanced Filtering with .filter()
- Excluding Elements with .not()