user3712856
user3712856

Reputation: 13

remove specific element loaded from ajax

hello I have a item list div in which items are listed by ajax with no problem. without page refreshing, I want to remove specific div from the list by 2nd ajax call.

<div id="itemList">
  <!-- these items are loaded by ajax -->
  <div id="item-1">Item 1</div>
  <div id="item-2">Item 2</div>
  <div id="item-3">Item 3</div>
</div>

1st ajax call

$.ajax({
  type: "POST",
  url: '/path',
  dataType: "json",
  data: {list: important},
  cache: false,
  success: function(result){
    $("#itemList").prepend(result.html);
  }
});

2nd ajax call

$.ajax({
  type: "POST",
  url: '/path',
  dataType: "json",
  data: {list: update},
  cache: false,
  success: function(result){
    // try to remove the specific item. failed.
    $("#item-"+ result.id).remove();
  }
});

can anyone help me? thanks.

Upvotes: 1

Views: 939

Answers (1)

Ty Bailey
Ty Bailey

Reputation: 2432

Because the list item is added via AJAX the DOM doesn't actually register it on page load. You'll need to target the parent element first like so:

$.ajax({
  type: "POST",
  url: '/path',
  dataType: "json",
  data: {list: update},
  cache: false,
  success: function(result){
      $('ul#itemList').find('#item-"+ result.id').remove();
  }
});

Upvotes: 1

Related Questions