jquery – How to add a class to multiple cached elements at once?

Question:

In jQuery, we can add CSS classes to multiple elements, but with the element already cached in a variable, how can we perform the same operation?

Example:

// adicionar classe a ambos os elementos
$('#myEle, #anotherEle').addClass('johnDoe');

Cached elements:

var $ele1 = $('#myEle'),
    $ele2 = $('#anotherEle');

// adicionar classe a ambos os elementos
$ele1.addClass('johnDoe');
$ele2.addClass('johnDoe');

How to move the addition of a CSS class to $ele1 and $ele2 to a line?

Answer:

jQuery contains a method, .add() , which allows you to group several jQuery objects that represent a group of DOM elements into a single object:

jQuery API Documentation: .add()

Example:

var $ele1 = $('#myEle'),
    $ele2 = $('#anotherEle');

// adicionar classe a ambos os elementos
$ele1.add($ele2).addClass('johnDoe');

Working with elements already in cache, it will be useful to know that you can cache $ele1 and $ele2 in case they get called multiple times:

var $elements = $ele1.add($ele2);

$elements.addClass('johnDoe');
Scroll to Top