views:

57

answers:

3

There are some times when I find myself repeating a selector several times. Should I be somehow storing a jquery object to a variable and then just using that one? As a quick example, what about the following?:

$('a.contactus).css('padding', '10px');
$('a.contactus).css('margin', '4px');
$('a.contactus).css('display', 'block');

Now I know this isn't a great example, since effectively you could just chain each css function. But suppose in between each of those was a conditional statement or something to stop you from chaining.

Can I store a jquery object in a variable? And if so, when should I/ can I?

+1  A: 

You can do this

var myvar = $('a.contactus');
myvar.css('padding', '10px').css('margin', '4px').css('display', 'block');

but for readability i do this

var myvar = $('a.contactus');
myvar.css('padding', '10px')
  .css('margin', '4px')
  .css('display', 'block');

basically every time you use $(someselector) you iterate through the dom. If you can you should store the element reference.

John Hartsock
It should be noted that neither of these is a good solution for this example (see the other answers)...but also *please* make sure your answer is at least correct if it's accepted.
Nick Craver
+4  A: 

When reusing it more than once (and you can't chain) storing it in a variable isn't a bad idea, the more often it's used or the more expensive the selector, the better idea storing it as a variable becomes. For example the performance of $(this) a few times is trivial, but the performance of $("[attr=val]") is very poor and should absolutely be cached if reused. If in doubt, cache it as a variable.


Just another tip, in that example you can also pass an object to .css():

$('a.contactus').css({ padding: '10px', margin: '4px', display: 'block' });
Nick Craver
+3  A: 

Should I be somehow storing a jquery object to a variable and then just using that one?

You should for the sake of performance when possible. You can for example re-write your code like this:

var $el = $('a.contactus');
$el.css('padding', '10px');
$el.css('margin', '4px');
$el.css('display', 'block');

You can make it even shorter like this:

$el.css({
  padding: '10px',
  margin:'4px',
  display: 'block'
});

Storing common/repetitive selector in a variable is also useful when writing jquery plugins to store the $(this) in a variable.

Sarfraz
You should no always store a reference, unless it's used more than once it's *worse* for performance.
Nick Craver
@Nick Craver: Yeah true agreed.
Sarfraz