Filtering Traversed Elements with jQuery

In dynamic web applications like WordPress themes, PHP-driven templates, or plain JavaScript interfaces, you often need to refine a jQuery selection to a precise subset. jQuery’s filtering methods let you narrow down matched elements based on CSS selectors, element state, DOM relationships, or positional logic. Whether you’re highlighting the first active menu item in a PHP-rendered navigation or excluding comments in a WordPress loop, these filtering methods keep your code brief and performant.

jQuery Filtering Methods

Here are the core filtering methods for refining a jQuery collection:

  • filter(selector): Retains only those elements in the current set that match the selector.
  • not(selector): Excludes elements matching the selector from the current set.
  • has(selector): Keeps elements that contain at least one descendant matching the selector.
  • is(selector): Returns true if any element in the set matches the selector (for condition checks).
  • first(): Reduces the set to the first element only.
  • last(): Reduces the set to the last element only.
  • eq(index): Selects the element at the specified zero‑based index.
  • even(): Selects elements at even indices (0, 2, 4…).
  • odd(): Selects elements at odd indices (1, 3, 5…).
  • slice(start, end): Selects a subset of elements within the specified range.
  • end(): Reverts to the previous jQuery object in the chain.
  • add(selector): Adds more elements to the current set.
  • addBack(): Includes the previous set of elements in the current chain.

Using filter() to Narrow Your Set

The filter() traversing method refines an existing jQuery collection by keeping only those elements that match a given selector. It is perfect for targeting menu items, form inputs, or custom widget wrappers in a blog sidebar.

filter() Example

$(function () {
	$('#highlight-active').on('click', function () {
		// Filter items with (.active) class and highlight
		$('.item').filter('.active').addClass('highlight');
	});
});

Key Points

  • The filter() method accepts any valid selector or callback function.
  • It also supports chaining e.g. $('.item').filter(':visible').css(...).

Excluding Elements with not()

To remove unwanted nodes from a selection—such as filtering out disabled inputs or excluding admin-only notices—use not() on your jQuery object.

not() Example

$(function () {
	$('#highlight-nonactive').on('click', function () {
		// Exclude (.active) items and highlight the rest
		$('.item').not('.active').addClass('highlight');
	});
});

Key Points

  • The not() method removes matching elements from the set.
  • Accepts selectors, elements, or callback functions.
  • Great for filtering selections after complex traversals.

Selecting Parents with has()

Use has() method to select elements that contain specific elements inside them. For example, you can use it to highlight all posts that have images inside them. It looks for elements that have certain descendants and returns the parent elements that match.

has() Example

$(function () {
	$('#highlight-with-badge').on('click', function () {
		// Highlight those elements that have a (.badge)
		$('.item').has('.badge').addClass('highlight');
	});
});

Key Points

  • The has() method returns elements with at least one matching descendant.
  • Efficient for complex DOM checks without manual loops.
  • It is chainable with traversal methods e.g. $('.gallery').find('li').has('a.lightbox').

Conditional Checks with is()

Use is() method to test if any element in a jQuery set matches a selector. It is ideal for branching logic in plugin scripts or theme functions.

is() Example

$(function () {
	$('.item').on('click', function () {
		// Use is() to test the clicked element
		if ($(this).is('.active')) {
			$(this).addClass('highlight');
		} else {
			alert('This item is not active.');
		}
	});
});

Key Points

  • The is() method returns a Boolean, not a jQuery object.
  • It also supports any selector, from pseudos to custom classes.
  • Perfect for guard clauses and conditional plugin behavior.

Position-Based Filtering

To pick elements by their position in the set, first, last, or an arbitrary index, jQuery provides handy shorthands:

Traversal Filtering With first() Method

The first() method selects the first element from a set of matched elements.

first() Example

$(function () {
	$('#highlight-first').on('click', function () {
		// Highlight the first item
		$('.item').first().addClass('highlight');
	});
});

Traversal Filtering With last() Method

The last() method selects the last element from a set of matched elements.

last() Example

$(function () {
	$('#highlight-last').on('click', function () {
		// Highlight the last item
		$('.item').last().addClass('highlight');
	});
});

Traversal Filtering With eq() Method

The eq() method selects a specific element from a set of matched elements based on its index.

eq() Example

$(function () {
	$('#highlight-third').on('click', function () {
		// Highlight item at index 2 (third item)
		$('.item').eq(2).addClass('highlight');
	});
});

Key Points

  • The first() and last() methods are zero-cost aliases to eq(0) and eq(-1) respectively.
  • The eq(n) method accepts negative indices to count from the end.

Index Parity Filtering

For alternating styles like striped tables, zebra lists, or every-other-item effects, use the jQuery even() and odd() filtering methods to split based on element index.

Traversal Filtering With even() Method

The even() method selects elements at even indexes (0-based) from a set of matched elements.

even() Example

$(function () {
	$('#highlight-even').on('click', function () {
		// Highlight Even Items
		$('.item').even().addClass('highlight');
	});
});

Traversal Filtering With odd() Method

The odd() method selects elements at odd indexes (0-based) from a set of matched elements.

odd() Example

$(function () {
	$('#highlight-odd').on('click', function () {
		// Highlight Odd Items
		$('.item').odd().addClass('highlight');
	});
});

Key Points

  • The even() method selects indices 0, 2, 4…, whereas the odd() method selects 1, 3, 5… indices.
  • Both these traversal filtering methods saves manual index checks inside each() loops.

Selecting a Subset with slice()

The slice() method lets you select a subset of matched elements by specifying a start and optional end index. It works similarly to JavaScript array slicing, helping you focus on a specific portion of the selection.

slice() Example

$(function () {
	// Highlight slice from index 1 to 4 (2nd to 4th item)
	$('#slice-range').on('click', function () {
		$('.item').slice(1, 4).addClass('highlight');
	});
	// Highlight slice starting from index 2 (3rd item onward)
	$('#slice-start').on('click', function () {
		$('.item').slice(2).addClass('highlight');
	});
});

Key Points

  • The slice() method accepts both positive and negative indices.
  • Negative index counts from the end: .slice(-2) selects the last two items.
  • Useful for partial selections and range-based filtering.

Reversing Traversal with end()

The end() method is used to return to the previous jQuery object in the chain. It’s particularly helpful when chaining multiple traversal methods and needing to go back a step.

end() Example

$(function() {
	$('#noEnd').click(function(){
		// Only children are highlighted, not parents
		$('.container')
		  .find('.item')
		  .addClass('highlight-child')
		  .addClass('highlight-parent');
	});
	$('#withEnd').click(function(){
		// Selection reverts to (.container), highlighting both children and parents
		$('.container')
		  .find('.item')
		  .addClass('highlight-child')
		  .end()
		  .addClass('highlight-parent');
	});
});

Key Points

  • The end() method reverses the most recent destructive traversal methods.
  • It preserves chainability while simplifying re-selection.
  • Also, it does not work after methods like filter() or not() as they don’t store a previous object.

Combining Sets with add()

The add() method merges additional elements into an existing jQuery object, allowing unified actions across both sets.

add() Example

$(function() {
	$('#highlight-btn').on('click', function() {
		// select featured items, add popular items, then highlight both
		$('.featured')
			.add('.popular')
			.addClass('highlight');
	});
});

Key Points

  • The add() method accepts a selector, DOM element, jQuery object, or HTML string.
  • It is useful for combining multiple matches before performing actions.
  • It also supports context-specific selections.

Include Previous Selection with addBack()

The addBack() method adds back the previous set of elements to the current one, especially after a destructive traversal like find().

addBack() Example

$(function() {
	$('#boldItems').on('click', function() {
		// only list items become bold
		$('.box').find('li').addClass('bold');
	});

	$('#boldItemsBox').on('click', function() {
		// Bold items, then addBack() brings the .box into the set and highlights both items and box
		$('.box')
			.find('li').addClass('bold')
			.addBack().addClass('highlight-box');
	});
});

Key Points

  • The addBack() method brings back the previous matched set for combined operations.
  • It is commonly used with find(), children(), etc.
  • A modern replacement for the deprecated andSelf() method.

Pro Tip:

The jQuery methods filter(), not(), is(), and has() support both a CSS selector and a callback function. Use a selector for straightforward filtering, or pass a function when you need custom, logic-based matching.