Allain Lalonde Allain Lalonde - 1 year ago 203
jQuery Question

Does jQuery do any kind of caching of "selectors"?

For example, will the first piece of code perform a full search twice, or is it smart enough to cache results if no DOM changes have occurred?

if ($("#navbar .heading").text() > "") {
$("#navbar .heading").hide();


var $heading = $("#navbar .heading");

if ($heading.text() > "") {

If the selector is more complex I can imagine it's a non-trivial hit.

Answer Source

jQuery doesn't, but there's the possibility of assigning to variables within your expression and then use re-using those in subsequent expressions. So, cache-ifying your example ...

if ((cached = $("#navbar .heading")).text() > "") {

Downside is it makes the code a bit fuglier and difficult to grok.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download