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.
It should be
$(this).parent().parent().remove();
You'd be better off tackling this by setting an ID for the comment in your code.
For example:
<div class="aComment" data-comment-id="5">
Then using this ID with your AJAX request and response.
A little more work, but it's more robust (IMO)
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're trying to remove it on a click:
$(".aComment a").on('click', function(){
$(this).closest(".aComment").remove();
});
http://jsfiddle.net/gaQuu/