1

I am trying to delete parent element with all of its children after one of the child is actually clicked on HTML:

<div class='container'>
    <span class='content' id='1'>Lorem</span>
    <span class='content' id='2'>Ipsum</span>
    <span class='content' id='3'>Dolor</span>
    <span class='content' id='4'>Sit</span>
    <span id='delete'>Delete</span>
</div>

jQuery:

$("#delete").click(function() {
  var name = $(this).siblings("#1").text();
  var surname = $(this).siblings("#2").text();
  var add = $(this).siblings("#3").text();
  var all = $(this).siblings("#4").text();
  $.ajax({
    data: {
      'name': name,
      'surname': surname,
      'add': add,
      'all': all
    },
    success: function(data) {
      $(this).siblings().remove(); // context of 'this' lost? doesnt work
      $(this).parent().remove();

    }
  });
});

Bear in mind. There is a few of those elements with class container having the exact same structure.

3 Answers 3

1

Store the value of this in a variable outside of the success callback scope.

$("#delete").click(function() {
  var self = this;
  // ...

  $.ajax({
    data: {},
    success: function(data) {
      $(self).siblings().remove();
      $(self).parent().remove();
    }
  });
});

It's worth pointing out that removing the parent element will also remove all of the children elements anyways. This means that you don't have to remove the sibling elements before removing the parent element.

$(self).parent().remove(); // No need to remove siblings, they will be removed.

However, you may want to remove the sibling elements, and then unwrap the element. In doing so, you can preserve the #delete element (if that's what you're trying to do).

$(self).siblings().remove();
$(self).unwrap();
1
  • 1
    That is exactly what I was looking for. I want to remove everything, so $(self).parent().remove(); with storing the value of $(this) works just fine.
    – Croolman
    Nov 29, 2015 at 20:47
1
 $("#delete").click(function() {
  var elem = $(this);
  //Other code
  $.ajax({
    data: {},
    success: function(data) {
      elem.siblings().remove();
      elem.closest(".container").remove();
    }
  });
-1

Have you tried something like this

 $(".content").children().hide(); 
2
  • Hide is not removing/deleting the elemnts Nov 29, 2015 at 20:47
  • 1
    Since there is many more elements with content class. I'd unintentionally hide all of them.
    – Croolman
    Nov 29, 2015 at 20:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.