views:

52

answers:

4

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?

+4  A: 

#div1 a matches anchors in this markup:

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

JS..

$(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');
   });
});
meder
+2  A: 

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.

CMS
A: 

Live everyone else says: Use the live method.

fernyb
A: 

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

Ajay