14

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 :)

1

5 Answers 5

17

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...)

Sign up to request clarification or add additional context in comments.

Comments

7

jQuery's add

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

Comments

7

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');

Comments

1

If you already have the selectors stored just apply the fadeTo to each one individually. JQuery will just have to parse the selector anyway...

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

2 Comments

@user690214: I cant image one fadeTo call on multiple elements is going to be any better. It still have to do the fade twice - once for each element - somewhere along the line
@user690214 Here is a jsperf to show the performance difference between using one fadeTo and using two of them. Also tested is using an array of DOM elements as the selector: jsperf.com/jquery-fadeto-once-vs-twice (seems like the array selector is the fastest: $([sel1[0], sel2[0]]).fadeTo...)
1

Try this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.