Store Jquery Selector in Variable

Store jquery selector in variable

You have a fundamental misunderstanding of what

variableName = $("selector here");

does. It does not "store the selector." It runs the selector you give against the current elements in the DOM, creates a jQuery object, puts the matching elements in the jQuery object, and gives you a reference to that jQuery object. The selector is not stored (modulo jQuery internals).

So given:

<body>
<div class="foo">x</div>
</body>

Then:

var $divs = $("div.foo");
console.log($divs.length); // 1

Gives us this:

$divs jQuery object pointing at one div in the DOM

If we then add another matching div:

$('<div class="foo"></div>').appendTo(document.body);

Our $divs still only points to the first one; adding another matching element to the DOM had no effect on the jQuery object referenced from $divs.

$divs jQuery object pointing to one div, but there are two in the DOM

If we re-run the query at that point:

$divs = $("div.foo");

...then we have:

$divs jQuery object pointing at both divs in the DOM

If you have a jQuery object containing a DOM element, and you add descendant elements to that DOM element, then using that jQuery object with (say) .find will see the descendants. That's because the parent DOM element is already there in the jQuery object. E.g., adding a span to one of the divs that we already reference from our jQuery object:

$divs jQuery object pointing at both divs in the DOM, one has a span now

If we were to use .find on $divs at that point looking for a span, we'd find it, because it's a descendant of one of the elements we already had a reference to.

If you want to re-run the DOM search again later to look for matching elements, you just use $() again; this is implicit in the above, but for clarity:

var $divs = $("div.foo");
console.log($divs.length); // 1
$('<div class="foo"></div>').appendTo(document.body);
console.log($divs.length); // Still 1
$divs = $("div.foo");
console.log($divs.length); // Now it's 2

So "storing a selector," when needed, is a matter of storing the selector string somewhere, not the jQuery object.

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

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.

How to store jQuery selector in a variable?

The variables in the second piece of code contain jQuery objects which wrap the DOM Elements.

So if you wanted to set innerHTML property you could use the jQuery function .html().

$consoleDisplayHTML.html(messages.pop().content);
$watchedFolderHTML.html(watchedFolder);

If you want to assign yourself the inner HTML to the Dom Elements you can extract the wrapped element from the jQuery object and set it to the innerHTML property.

$consoleDisplayHTML.get(0).innerHTML = messages.pop().content;
$watchedFolderHTML.get(0).innerHTML = watchedFolder;

In regard to your edit: there could be a number of reasons the above snippets don't work. Usually for this kind of problem if you execute that code directly in <head> without surrounding it in a document ready callback the code will be executed as soon as it is reached by the browser but the elements in the DOM are not yet created. To avoid usage of a callback you may try to move to the bottom of the page the javascript code you wrote for example.

Here's a good old document ready callback:

jQuery(function ($) {
var $consoleDisplayHTML = $('#consoleDisplay');
var $watchedFolderHTML = $('#watchedFolder');

$consoleDisplayHTML.html(messages.pop().content);
$watchedFolderHTML.html(watchedFolder);
});

Is storing jQuery elements in variables more efficient?

It is always good practice to cache your nodes. The amount of work the JS engine has to do to locate the nodes is more expensive than the memory that you will use storing the node (of course unless you are storing a massive DOM tree or something).

So the winner is:

var myElement = $("#the-name-of-my-element")

myElement.doSomethingOnce;
myElement.doSomethingTwice;
...
myElement.doSomethingTenTimes;

Storing jQuery selector into a variable is not working?

When you cache a jquery selector in a variable it stores the current jquery object returned.
So, when you first cache the variable, there are no .mtitle elements in the DOM as you add them later.
Its not an error just more of a conceptual problem you are facing!

How to use JavaScript variables in jQuery selectors?

var name = this.name;
$("input[name=" + name + "]").hide();

OR you can do something like this.

var id = this.id;
$('#' + id).hide();

OR you can give some effect also.

$("#" + this.id).slideUp();

If you want to remove the entire element permanently form the page.

$("#" + this.id).remove();

You can also use it in this also.

$("#" + this.id).slideUp('slow', function (){
$("#" + this.id).remove();
});

Which is faster in jquery: $(selector) or selector as an object variable?

If you're going to be re-selecting the same element multiple times, then storing the jQuery object in a variable is always much faster as it negates the need to read data from the DOM, which is comparatively much slower.

Storing $(this) in a variable

var element = $(this)

Then you can use element instead of $(this). You don't have to insert element into $() anymore.

For example : element.remove() instead of $(this).remove()

Performance of jQuery selectors vs local variables

Reusing the selector reference, your first case, is definitely faster. Here's a test I made as proof:

http://jsperf.com/caching-jquery-selectors

The latter case, redefining your selectors, is reported as ~35% slower.



Related Topics



Leave a reply



Submit