jQuery variable and object caching
- by niksy
This is something that has been bugging me some time and every time I found myself using different solution for this.
So, I have link in my document which on click creates new element with some ID.
<a href="#" id="test-link">Link</a>
For the purpose of easier reusing, I would like to store that new elements ID in a variable which is jQuery object
var test = $('#test');
On click I append that new element on body, new element is DIV
$('body').append('<div id="test"/>');
And here goes the main "problem" - if I test this new elements length with test.length it first returns 0 and later 1. But, when I test it with $('#test').length it returns 1 from the start.
I suppose it is some caching mechanism and I was wondering is there better, all-around solution which will allow to store elements in variables in the start for later repurpose and in the same time work with dynamically created elements.
Live, delegate, something else? What I do sometimes is create string and add it to jQuery object but I think this is just avoiding the real issue. Also, using .find() inside another jQuery object.
Thanks in advance.