1

Does caching jquery selectors keep a dynamic copy of that selector or just that selector at the time of assignment? What I mean is that I cache the variable at the top of my document and later try to use it and it just won't work.

var $cell = $('#grid .cell');

// much later in code

$cell.each(function (index) {
  // random code
});

if I change out the variable for the jquery selector $('#grid .cell').each().. it works. The only reason I can come up with is that the selectors contents have changed since I assigned the variable

Stephen Bolton
  • 365
  • 2
  • 10

2 Answers2

3

Does caching jquery selectors keep a dynamic copy of that selector or just that selector at the time of assignment?

No.

It does not re-evaluate when you add more stuff to the HTML page.

The selector would have the same value even if you change the content of the page and add more elements that could match the selector. Check this.

Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52
0

The value of the variable $cell is declared in your "var" statement, and never updated.

See this snippet for a real step-by-step visual.

var $x = $('.x');

setInterval(function(){
  $('.content').append('<div class="x">');
  console.log($x);
}, 1000);

In the first statement, $x is a selection of all the matching elements - none, in this case. In the loop, I'm appending a new matching element to the document every second, but since I'm never updating the value of $x, it logs the same exact data.

full JSFiddle: http://jsfiddle.net/kd2yvjje/5/embedded/result/

Christine Cha
  • 505
  • 3
  • 11