How to Find the Intersection of Two jQuery Objects

Finding the intersection of two jQuery objects—identifying the DOM elements shared by both collections—is a frequent requirement when manipulating targeted selections. This article explains the most efficient and standard way to retrieve intersecting elements using jQuery's built-in .filter() method, covers legacy and native alternatives, and highlights performance considerations.

The Standard Method: Using .filter()

Since jQuery 1.8, the standard .filter() method directly accepts another jQuery collection or an array of DOM elements. When passed another jQuery object, .filter() compares the elements in the first set and retains only those that are present in the second set.

// Select two sets of elements
const $setA = $('.featured-items');
const $setB = $('.active-items');

// Find the intersection
const $intersection = $setA.filter($setB);

// Apply actions to the matching elements
$intersection.css('border', '2px solid green');

In this example, $intersection contains only the elements that have both the .featured-items and .active-items classes.

Alternative Method: Using .filter() with a Function

If you are working with an older version of jQuery (pre-1.8) or need custom comparison logic, you can pass a function to .filter() that checks if each element exists in the second collection using .index() or .is():

const $intersection = $setA.filter(function() {
    return $setB.index(this) !== -1;
});

Using .is(this) inside the filter loop is another functional alternative:

const $intersection = $setA.filter(function() {
    return $setB.is(this);
});

Vanilla JavaScript Alternative

For improved performance across very large DOM collections, you can convert both jQuery objects into native arrays and leverage JavaScript's built-in Set and Array.prototype.filter() methods, then wrap the result back into a jQuery object:

const setBElements = new Set($setB.get());
const intersectionElements = $setA.get().filter(element => setBElements.has(element));

const $intersection = $(intersectionElements);

Using a Set provides \(O(1)\) lookup time per element, making it the fastest option for processing extensive lists.

Performance Optimization

When computing an intersection using the standard $setA.filter($setB) syntax:

  • Filter the smaller set: Always run .filter() on the smaller collection and pass the larger collection as the argument (e.g., if $setA has 5 elements and $setB has 500, $setA.filter($setB) requires fewer iterations than $setB.filter($setA)).
  • DOM caching: Avoid running selector queries inline within the filter operations. Store your selections in variables prior to computing the intersection.