skndstry
skndstry

Reputation: 671

Using JQuery to select links created by JQuery

So if a button is clicked on my site, a new link is generated:

<a name="2" class="cld">mylink</a>

Now, is there any way I can use a selector like

$('.cld') 

to select this link that wasn't there when the page loaded?

I guess it's possible to use onClick as an attribute in the link tag. If so, could you tell me how. If the link is clicked, it should remove a div from the DOM with the id 'div-nr', nr being the same as the name attribute in the link.

I guess it's not that hard, but I've been struggling with this for the past hour and I would really appreciate a solution to this problem. Thanks!

Upvotes: 1

Views: 75

Answers (4)

Felix Kling
Felix Kling

Reputation: 816404

It depends on when you use the selector:

  • If you use it after the link was generated, you are fine.
  • If you want to bind an event handler before the link was generated, have a look at live() and delegate().

Upvotes: 3

rsenna
rsenna

Reputation: 11963

You could use jQuery live events.

A regular .click() won't work for dynamically generated entities.

Upvotes: 2

Nick Craver
Nick Craver

Reputation: 630389

You can use .live() and .delegate() to handle events on current and future elements matching the selector, for example:

$('.cld').live("click", function() {
  $("#div-nr").remove();
});

Or with .delegate():

$('#containerID').delegate('.cld', 'click', function() {
  $("#div-nr").remove();
});

Upvotes: 2

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114367

The best thing to do is to give all of your default links their own class, and the new ones a different class. Then select on the original class.

Upvotes: 2

Related Questions