Ajay
Ajay

Reputation: 7428

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?

Upvotes: 0

Views: 1500

Answers (4)

Ajay
Ajay

Reputation: 7428

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

Upvotes: 0

fernyb
fernyb

Reputation: 983

Live everyone else says: Use the live method.

Upvotes: 1

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827606

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.

Upvotes: 2

meder omuraliev
meder omuraliev

Reputation: 186632

#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');
   });
});

Upvotes: 5

Related Questions