Using $(document).ready(function() on elements that are created via DOM modification ?
HI all you jQuery gurus out there,
I have a very detailed question and I hope I'll be able to explain it properly and also get an answer:
I use the following code to add a "click" behaviour to an element:
- $(document).ready(function(){
$("#element_id").click (function(){
- ...... do something ....
- });
- });
So far so good, works fine.
I also use the following code to clone a node and append it to the DOM:
- function addRowJob(r){
var root = r.parentNode;//the root
var allRows = root.getElementsByTagName('fieldset'); //the fieldset' collection
- var cRow = allRows[0].cloneNode(true)//the clone of the 1st fieldset
- ... do some more stuff...
- root.appendChild(cRow); //appends the cloned row as a new fieldset
- }
Part of the node I clone is the element from the first piece of code I quoted. The addRowJob function also changed the ID of every element in the node I cloned. This way all IDs remain unique. Lets say the element in question has the ID "#element_id". Now I clone the node (which includes the element) and the cloned element gets its ID changed to "#element_id_new".
Of course I now want this newly append element ("#element_id_new") to have a click event attached to, but even if extend my $(document).ready(function() to:
- $(document).ready(function(){
- $("#element_id").click (function(){
- ...... do something ....
- });
- $("#element_id_new").click (function(){
- ...... do something ...
- });
- });
I simply doesn't work for the appended element.
My guess is that the $(document).ready(function(){ only fires when the document is finished loading. At this stage there is no element with the ID "#element_id_new" and therefore the click event can't be attached to the element. Makes senses...
But how do I get this click event attached to the newly appended element with the ID "#element_id_new"?
I hope I didn't make this sound too confusing and you guys understand what I mean.
Cheers,
Bjorn