views:

486

answers:

1

Hi,

I'm using jQuery to load ajax content on to a page. However, trying to use jQuery's .remove() function doesn't seem to be working to remove the dynamically loaded element.

My example function:

function deletePerson(personID){
    if (confirm("Are you sure you want to permanently delete this person?\nYou cannot undo this action.")){
      $.post("ajax/personsDelete.php", { personNo: personID },
          function(data){
              $('#person' + personID).remove();
              alert("Response: " + data);
          });
    }
}

How can I remove dynamically loaded elements with jQuery?

A: 

Change the context of the selector to look at the response, adding ,data:

function deletePerson(personID){
    if (confirm("Are you sure you want to permanently delete this person?\nYou cannot undo this action.")){
      $.post("ajax/personsDelete.php", { personNo: personID },
          function(data){
              $('#person' + personID, data).remove();
              alert("Response: " + data);
          });
    }
}

Since it isn't added to the document yet, the default selector you're invoking won't find it:
$('#person' + personID) is the same as $('#person' + personID, document)

Nick Craver