ozzii ozzii - 3 months ago 9
HTML Question

JQuery Remove Parent List Item

I have the following markup:

<ul class="media-list">
<li class="media post">
<div class="media-left">
<a href="#"></a>
</div>
<div class="media-body">
<div class="post-content">
<p></p>
</div>
<div class="post-actions clearfix">
<ul class="list-unstyled list-inline">
<li>
<a class="js-delete-post" data-post-id="24" href="#">
Delete
</a>
</li>
</ul>
</div>
</div>
</li>
<li class="media post">
...
</li>
</ul>


When I click js-delete-post anchor I want to remove the parent li with class "media post".

The following Jquery simply traverses one level up and removes the li of the js-delete-class. How do I traverse an additional level up to remove the post.

$(".js-delete-post").click(function (e) {
var a = $(this); // "this" is the <a>

a.parents("li").fadeOut(function () {
$(this).remove();
});
});

Answer

You want closest instead of parents and then select it by the classes too.

a.closest("li.media.post").fadeOut(function() {
    $(this).remove();
});