Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to re-use jQuery-selected elements

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 element is. For example:

$('#my_div').css('background','red');
//some other code
$('#my_div').attr('name','Red Div');

vs.

myDiv = $('#my_div');
myDiv.css('background','red');
//some other code
myDiv.attr('name','Red Div');

I assume the second example is more efficient because the element #my_div doesn't have to get found more than once. Is that correct?

Similarly, is it more efficient to first save $(this) in a varaible, such as 'obj', and then reuse 'obj' rather than using $(this) over and over? In this case, jQuery isn't being forced to find an element over and over again, but it IS being forced to convert this to a jQuery object [$(this)]. So as a general rule of thumb, should a jQuery object ALWAYS be stored in a variable if it will be used more than once?

like image 261
maxedison Avatar asked Mar 28 '11 16:03

maxedison


People also ask

Which jQuery method is used to set one or more style properties for selected elements?

jQuery css() Method The css() method sets or returns one or more style properties for the selected elements.

What does $() return in jQuery?

$() does not return the jQuery function, (which is $ itself,) but returns a wrapped set, with all those helpful methods on it.

How will you select all the div elements on the page using jQuery?

The jQuery syntax is a little simpler, but not much more: $("div") is the jQuery equivalent to document. getElementsByTagName("div") . Here is the API documentation on jQuery's element selector: “Description: Selects all elements with the given tag name.


1 Answers

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.

like image 166
wsanville Avatar answered Oct 31 '22 19:10

wsanville