JQuery Variable and Object Caching
This is what bugged me for a while, and every time I found myself using a different solution for this.
So, I have a link in my document that, when clicked, creates a new item with some ID.
<a href="#" id="test-link">Link</a>
For the sake of easier reuse, I would like to store this new element id in a variable, which is a jQuery object
var test = $('#test');
On click I add this new element to body, new element is DIV
$('body').append('<div id="test"/>');
And here is the main problem - if I test this new length of elements with test.length it returns 0 first and later 1. But when I test it with $ ('# test'). length, it returns 1 from the beginning.
I suppose this is some kind of caching mechanism, and I was wondering if there is a better solution that will allow you to store elements in variables at the beginning for later repurposing and at the same time work with dynamically created elements.
Live, delegate, something else? Sometimes I create a string and add it to the jQuery object, but I think this just fixes the real problem. Also, using .find () inside another jQuery object.
Thanks in advance.
a source to share
I think there are a couple of problems here. Correct me if this is not the order of events in your script.
First, a request is made for the element with the id tag
// gets 0 elements, and it will not update since it not a live object.
var test = $("#test");
Second, a new document with an id tag is created and inserted into the document.
$('body').append('<div id="test"/>');
In this case, the variable test will not update and still has 0 items.
Instead, you can create and cache dynamically created elements even before inserting them into the document.
// Caching the object, though it has not been inserted into the document yet.
var test = $("<div id='test'></div>");
// Append the cached object to body on some click event
$("body").append(test);
// Make some changes to the div directly without using the cached variable.
$("#test").text("wazza!");
// Let see if the cached variable has an updated value.
alert(test.text()); // alerts "wazza!"
a source to share