Reputation: 625
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.
Upvotes: 2
Views: 1658
Reputation: 141909
I think there are a couple of issues here. Correct me if this is not the order of events in your script.
First, a query is made for an element having the id test
// gets 0 elements, and it will not update since it's not a live object.
var test = $("#test");
Second, a new div with id test is created and inserted into the document.
$('body').append('<div id="test"/>');
The variable test will not update in this case and still has 0 elements.
Instead, you could 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's see if the cached variable has an updated value.
alert(test.text()); // alerts "wazza!"
Upvotes: 3
Reputation: 299218
when you are creating the query, you are storing a snapshot of the query in your variable. This is not a live query. So when the component is added, the query is not updated.
As a simple fix try this
function getTest(){
return $('#test');
}
now use getTest() instead of test
Upvotes: 0