I can imagine the correct answer to this based on theory, but I\'m just looking for some confirmation. I\'m wondering what the most efficient way to re-use a jQuery-selected ele
One thing that I find is generally overlooked is just how powerful jQuery chains are. It may not be so noticeable, but since jQuery caches your wrapped elements within a chain, you can modify elements, go into a more specific subset, modify, then go back up into a a general superset without much overhead.
I expect something like (pardon the example)
$('#myDiv')
.addClass('processing')
.find('#myInput')
.hide('slow')
.end()
.removeClass('processing')
;
to be better performance-wise than even
var $myDiv = $('#myDiv').addClass('processing');
var $myInput = $('#myDiv #myInput').hide('slow');
$myDiv.removeClass('processing');
This also holds for applying the jQuery function to elements returned in an event handler. Try to avoid applying $(...) too many times, because this is slow. Instead create a variable that contains the result of $(...). Good practice is to start the variable with a $, which gives a hint about the jQuery object inside the variable.
$('a').click(function(){
var $this = $(this);
$this.addClass("clicked");
$this.attr("clicked", true);
});
if you're using jQuery selector (like $('#element')
), then yes, you should always store your results.
if you're using object and wrapping it in jQuery (like $(this)
), it's not necessary, because jQuery doesn't need to search for that element again.
You should write your code such that you limit the number of DOM traversals.
When you write something like this:
$('#my_div').css('background','red');
//some other code
$('#my_div').attr('name','Red Div');
You are finding #my_div
twice, which is inefficient.
You can improve this either by assigning the result of a selector (i.e. var x = $('.something')
) and manipulate the variable x
, or you can chain your method calls like this:
$('#my_div').css('background','red').attr('name','Red Div');
You'll see the above code used a lot, because you're finding the element once. The css()
method will apply a CSS style and return the actual result of $('#my_div')
, so you can invoke another method, in this case attr()
.
My preferred way of handling the re-use of selectors is to store them as a variable, and wrap my stuff in a closure.