Tutorial :jQuery Selection of elements created run time


I have the following scenario:

I have a div = "#div1" which is coded in html. I have populated this div with some data coming from a script service [ which means the "a's" are not there initially], and the data is appended to this div as

<a href=''>data1</a>  <a href=''>data2</a>  

I have a jQuery selector like :

$(document).ready(function(){     $("#div1 a").click(function(){        // do something     });  });  

This is not selecting the element. How do I overcome this problem?


#div1 a matches anchors in this markup:

<div id="div1"><a href="#">test</a></div>  


$(document).ready(function(){     $("#div1 a").click(function(){        alert('test');     });  });  

Please check for user errors/typos.

If you are appending data after an ajax call, you need to use .live:

$(document).ready(function(){     $("#div1 a").live('click', function(){        alert('test');     });  });  


The anchor elements don't exists yet when the click event handler is bound, but you can use the live method, which uses event delegation:

$(document).ready(function(){     $("#div1 a").live('click', function(){        // do something     });  });  

live will match current and future elements on the DOM.


Live everyone else says: Use the live method.


Yet another simple and obvious solution in this case would be to push the click registration until the data is completely rendered!

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »