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

Asked

Viewed 164 times

4

In jQuery, we can add CSS classes to multiple elements, but with the element already cached in a variable, as we can 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 add a CSS class to a line $ele1 and $ele2 ?

1 answer

5


jQuery contains a method, the .add(), which makes it possible to group several jQuery objects representing 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 cached, it will be useful to know that you can cache the $ele1 and the $ele2 in case they are called several times:

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

$elements.addClass('johnDoe');
  • 1

    good, did not know this class to work more than one element at a time...

  • 1

    @Leandroluk, Yes, I discovered the same when I asked the question/answer :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.