Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery, how to use multiple cached elements

For my project I'm using cached selectors to speed up, and see improvements: (to reduce searches inside the document)

var sel1 = $('#selector1');
var sel2 = $('#selector2');

how can I use cached selectors in this situation? for ex:

$('#selector1, #selector2').fadeTo(300, 1, 'linear');

It's just to polish up my code

Ty :)

like image 570
a clever name Avatar asked Dec 15 '11 20:12

a clever name


3 Answers

You can use .add() to "Add elements to the set of matched elements":

sel1.add(sel2).fadeTo(300, 1, 'linear');

Docs for .add(): http://api.jquery.com/add

.add() can take in:

  • a selector
  • DOM elements
  • jQuery objects
  • and selectors with context ($('<selector>', <context>))

You can also pass an array of DOM elements to jQuery:

var one = $('#one')[0],
    two = $('#two')[0];

$([one, two]).fadeTo(300, 1, 'linear');

Here is a demo: http://jsfiddle.net/3xJzE/

UPDATE

I created a jsperf of the three different methods that are currently answers: http://jsperf.com/jquery-fadeto-once-vs-twice (it seems like using an array selector is the fastest: $([one, two]).fadeTo...)

like image 146
Jasper Avatar answered Nov 04 '22 03:11

Jasper


jQuery's add

sel1.add(sel2).fadeTo(300, 1, 'linear');
like image 22
Dennis Avatar answered Nov 04 '22 02:11

Dennis


You can use .add() method for that;

sel1.add(sel2).fadeTo(300, 1, 'linear');

It'll be good if you add $ prefix when naming your variables. This way you can distinguish them from standart javascript objects. So this is better:

var $sel1 = $('#selector1');
var $sel2 = $('#selector2');

$sel1.add($sel2).fadeTo(300, 1, 'linear');
like image 7
Emre Erkan Avatar answered Nov 04 '22 03:11

Emre Erkan