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

4

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 do I add a CSS class to $ele1 and $ele2 to one row?

    
asked by anonymous 16.12.2013 / 17:24

1 answer

5

jQuery contains a method, .add () , which allows you to group multiple jQuery objects that represent a group of elements of the DOM on 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 cached, it will be useful to know that you can cache $ele1 and $ele2 in case they are called multiple times:

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

$elements.addClass('johnDoe');
    
16.12.2013 / 17:24