Always use jquery selectors or cache them in variables?

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').attr('something', 'something');

So often I like to cache my objects in variables:

$('#mybutton').click(function() {
    var msg = $('#message-box');
    // 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.


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.

Need Your Help

OpenGL Application Code in relation to GLSL

c++ opengl

I am having some difficulty understanding the connection between my OpenGL application and my GLSL files (.vert and .frag). I know how to create a vertex or fragment shader, and there is plenty of

document is an alias name?


Is document an alias of Sys.UI.DomElement in JavaScript?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.