Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove parent div by class name - jquery

Tags:

jquery

I have a remove link that will remove the current comment on my page. It uses ajax to change the database and upon success, I want to remove the div the comment resides in. Each comment on the page looks like this:

<div class="aComment">
    <span class="commentTitle">Posted by xxx at xxx - <a href="javascript:void(0)" class="deleteComment" data-commentid="anID"><img src="resources/images/delete_comment.png" title="Remove this comment" /></a></span>
    <span class="commentText">comment text here</span>
</div>  

I can't figure out how to remove the div once it has returned success. I've tried

$(this).parent().remove();

and no luck. $(this) refers to the anchor tag so parent() of the anchor should be the <div class="aComment"> right?

like image 987
Ronnie Avatar asked Oct 19 '25 02:10

Ronnie


2 Answers

Within your Ajax callback this does not refer to the anchor element, but even if it did, the .parent() method returns the immediate parent, i.e., the span element, not the div.

Assuming you have a reference to the anchor, you can say:

 $theAnchor.parent().parent().remove();  // get a's parent's parent

...but of course that is kind of brittle because if you later change the html structure you have to change the code to. So it is better to use .closest() to search up the tree to the nearest ancestor element that matches:

$theAnchor.closest("div").remove();

You don't show your click handler, but it'll need to be something like this:

$(".aComment a").click(function() {
   // keep a reference to the clicked a element for use
   // in the ajax callback
   var $theAnchor = $(this);

   $.ajax(/* your ajax parameters here */, function() {
      $theAnchor.closest("div").remove();
   });
});
like image 116
nnnnnn Avatar answered Oct 22 '25 04:10

nnnnnn


Use closest():

$(this).closest(".aComment").remove();

Example.

The parent of the a tag is the span. The div you are trying to remove is the parent of that span.

The reason for using this is simply because it's more convenient than using parent() twice.

like image 44
Purag Avatar answered Oct 22 '25 04:10

Purag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!