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
thisdoes 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:
…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:You don’t show your click handler, but it’ll need to be something like this: