Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to store the result of a JQuery selector in a variable?

Developers I know tend to call the same JQuery selectors over and over instead of 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 feels correct to me but maybe I'm missing something. This is a simple example, but I've seen $(this) repeated dozens of times in the same function.

What is the best practice for development with JQuery? Call selectors repeatedly or store in a variable?

like image 916
Joe B Avatar asked May 28 '15 19:05

Joe B


People also ask

Can you store a selector in a variable?

Can you store a Selector in a variable? Options are : Yes, in a UiElement variable.

Can jQuery selector be a variable?

Projects In JavaScript & JQueryYes, it is possible to pass a variable into a jQuery attribute-contains selector. The [attribute*=value] selector is used to select each element with a specific attribute and a value containing a string.

How can we store data in variable in jQuery?

jQuery(element). data(key,value); // Store arbitrary data associated with the matched elements. or declare your variable outside the function.

What does jQuery selector return?

The jQuery Object: The Wrapped Set: Selectors return a jQuery object known as the "wrapped set," which is an array-like structure that contains all the selected DOM elements. You can iterate over the wrapped set like an array or access individual elements via the indexer ($(sel)[0] for example).


1 Answers

The shown analysis is a micro optimization. Using $(this) repeatedly versus storing $(this) in a variable and reusing it will not cause a significant hit to performance.

The times you really want to store the result is when there is an actual selector in there. The only hit you are taking by repeatedly calling $(this) is calling the jQuery constructor function which is very lightweight.

So in this instance go with what reads better. If there really is a dozen occurrences of $(this) in a row, then there should have either been some storing of the variable as indicated, or more likely there was an opportunity to take advantage of chaining which was missed.

like image 55
Travis J Avatar answered Oct 21 '22 08:10

Travis J