2

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?

USA
  • 21
  • 1
  • 2
  • 1
    That should work fine, what value does personID contain and what does the html element look like? – Markus Hedlund Feb 16 '10 at 19:08
  • 1
    Are you sure personID contains the correct value inside the callback function? – tbreffni Feb 16 '10 at 19:09
  • can you show the code for the ajax load part? – GeekTantra Feb 16 '10 at 19:09
  • After reading this post: http://stackoverflow.com/questions/1903788/updating-jquery-tablesorter-plugin-after-removing-a-row-from-dom I have decided to just re-load the tab via `.load()`... Clunkier but more reliable. (I am using tablesorter with my table) – USA Feb 16 '10 at 19:13
  • 1
    It doesn't make any difference where the element came from, i.e. if it was on the page on load or was dynamically loaded. jQuery will look at the DOM as it is right then and remove the element. Almost definitely, you have the ID of the element incorrect. View the element with firebug and confirm that #person+personID could equal the ID you are trying to remove. – JAL Feb 16 '10 at 19:44

1 Answers1

3

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
  • 623,446
  • 136
  • 1,297
  • 1,155