views:

1087

answers:

3

jQuery selectors are wonderful, but I sometimes I find myself typing them over and over, and it gets a little annoying.

 $('#mybutton').click(function() {
    $('#message-box').doSomething();
    $('#message-box').doSomethingElse();
    $('#message-box').attr('something', 'something');
 });

So often I like to cache my objects in variables:

$('#mybutton').click(function() {
    var msg = $('#message-box');
    msg.doSomething();
    msg.doSomethingElse();
    // you get the idea 
});

Are there any pros or cons between these two patterns? Sometimes it feels like creating the variables is extra work, but sometimes it saves my fingers a lot of typing. Are there any memory concerns to be aware of? Do selectors clean up nicely after being used, whereas my bad coding habits tends to keep the vars in memory longer?

This doesn't keep me up at night, but I am curious. Thanks.

EDIT: Please see this question. It essentially asks the same thing, but I like the answer better.

+11  A: 

You should chain them:

$('#mybutton').click(function() {
  $('#message-box').doSomething().doSomethingElse().attr('something', 'something');
 });

If you need to do something over and over again and the functions don't return the jQuery object saving them in a var is faster.

Pim Jager
That definitely seems to be the jQuery way to do it.
ayaz
+1  A: 

I say go for it!

I do the same thing as you.

It makes my code more readable which makes me happy.

ewakened
+3  A: 

I usually chain them as per Pims answer, however sometimes when theres a lot of operations to be done at once, chaining can cause readability issues. In those cases I cache the selected jQuery objects in a variable.

Darko Z