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?
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();
});
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With