Is it possible to save the result of a jQuery selector in a variable?

The developers I know often repeat the same jQuery selectors, rather than storing the result in a variable. They are consistent with this approach.

For example, they do this:

var propName = $(this).attr('data-inv-name'); var propValue = $(this).attr('data-inv-value'); 

Instead of this:

 var current = $(this); var propName = current.attr('data-inv-name'); var propValue = current.attr('data-inv-value'); 

The latter approach seems correct to me, but maybe I missed something. This is a simple example, but I saw that $ (this) is repeated dozens of times in the same function.

What is the best practice for developing with jQuery? Are call switches repeated or stored in a variable?

+5
source share
3 answers

The analysis shown is a micro optimization. Reusing $(this) compared to storing $(this) in a variable and reusing it will not result in significant performance impacts.

The time at which you really want to save the result is when there is a real selector. The only hit you make by repeating the call to $(this) calls the jQuery constructor function, which is very easy.

So, in this case, move on to what is best read. If there really are a dozen occurrences of $(this) in a string, then there should have been either some storage of the variable, as indicated, or more likely, it was possible to take advantage of the chain that was skipped.

+8
source

If I am going to use the same selector more than two times, I always create a variable. The only change I would recommend is to use $ in front of your variable name to indicate that it is a jQuery object

 var $current = $(this); var propName = $current.attr('data-inv-name'); var propValue = $current.attr('data-inv-value'); 
+6
source

Theoretically, choosing a component many times requires more processes, and then using the one you already have ...

If you don’t have too many selectors in your page, the difference will be almost zero (I assume this is a more common case) ... Then you can think about what makes it more readable or easy to change ...

Sometimes you use the same element from a dozen lines, in which case I prefer to assign it to a variable, because when changing an element I will only need to change one line (the line that I assigned to the variable) ...

0
source

All Articles