bobighorus
bobighorus

Reputation: 1152

jquery event from a dynamically loaded element to its parent

I add dynamically the below HTML with the .load() function:

<div class="todelete"><a href="#" class="delete"></a></div>

Then I wish to do something like this:

$("a.delete").live('click', function() {
    $("a.delete").parent("div").remove();
});

but nothing; it seems that it doesn't know who "this" is referring to.

How can I fix this?

Thank you so much in advance.

Any help will be apreciated.

Upvotes: 1

Views: 56

Answers (3)

Jonas Stensved
Jonas Stensved

Reputation: 15306

You should reference it like this:

$("a.delete").live('click', function() { 
$(this).closest("div").remove(); 
})

For example, see: http://jsbin.com/urugow/edit#preview

UPDATE: Made a better example in jsbin

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337627

parent("div") will return you an array of all the div elements higher in the DOM tree from the current element. Try closest() instead, which will just return the single clsest div.

Also, use $(this) in your handler to only target the element which is being clicked on, rather than all .delete elements.

$("a.delete").live('click', function() {
    $(this).closest("div").remove();
});

Upvotes: 1

Ben
Ben

Reputation: 270

If you move your live() function to be nested inside the function that creates the div.todelete it should work.

From my experience you cannot access a dynamicly created div, unless you create the function at the time the div is created.

Upvotes: 0

Related Questions