JasonDavis
JasonDavis

Reputation: 48933

Remove items from the DOM that have been added with Javascript and jQuery?

I am working on a JavaScript/jQuery project that adds a set of divs and input fields to a page when a button is clicked, there is another button that removes these items from a page when that button is clicked.

My problem is it does not delete items from the page that have been added to the page after the page has loaded. So anything added to the page with Javascript is not removed with Javascript.

Below is the code I am using the .on jQuery event but it does not do what I explained.

How can I make the code below work on items that are added to the page with Javascript after the Dom has loaded?

// Remove "Deleted" Rows from View and mark as a Deleted item
$(".delete").on('click',function() {
    $(this).parents(".dnsRecord").addClass("deleted").find("input.delete").val("true");
    $(this).parents(".dnsRecord").find("span.undo").fadeIn('slow');
    PanelDNS.unsavedChanges = true;
});

Upvotes: 1

Views: 100

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

Use delegated event model of .on(), by passing the .delete selector as 2nd argument

$(document).on('click', '.delete', function() {
    $(this).parents(".dnsRecord").addClass("deleted").find("input.delete").val("true");
    $(this).parents(".dnsRecord").find("span.undo").fadeIn('slow');
    PanelDNS.unsavedChanges = true;
});

Upvotes: 2

Related Questions