JQuery selector caching

So, I know, if I use the selector more than once, it is better to cache it in a javascript variable. What if I want to perform the same action for multiple jQuery selectors that are stored in variables? ex

var $selector1 = $('#div1');
var $selector2 = $('#div2');
var $selector3 = $('#div3');
//do some work here on each individual div

//now I want to do this
$('#div1, #div2, #div3').addClass('myClass');

Is there a way to do this on three variables? (something like ($selector1, $selector2, $selector3).addClass('myClass');)

+3
source share
2 answers

You can use .add ()

$selector1.add($selector2).add($selector3).addClass('myClass');
+8
source

Of course you can use add():

$selector1.add($selector2).add($selector3).addClass('myClass');
+1
source

All Articles