ozzii ozzii - 3 months ago 14
CSS Question

JQuery removing wrong li

I have the following mark up:

<ul class="media-list">
<li class="media post">
<div class="media-body">
<div class="post-content">
<p>test</p>
</div>
<div class="post-files clearfix">
<p>Attached Files</p>
<ul class="list-inline">
<li>
<a class="js-delete-file" data-file-id="13" title="Delete" href="#">
<i class="fa fa-times" aria-hidden="true"></i>
</a>
</li>
</ul>
</div>
</div>
</li>
</ul>


When I click js-delete-file anchor I want to remove the immediate li this link is inside.

The following Jquery is removing the li with class "media-post" instead. How do I remove the li the link is inside?

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

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

Answer

Use closest() to:

get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

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

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

While .parents() is used to:

Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.


You could also use parent() singular in this particular case as well.

Given a jQuery object that represents a set of DOM elements, the parent() method traverses to the immediate parent of each of these elements in the DOM tree and constructs a new jQuery object from the matching elements.