I am trying to remove list_product
entire block if that particular delete
class is clicked. I am very new to jquery and still learning.
<div class='list_product'>
<div class='row'>
<div class='delete'>x</div>
<div class='title'>Standing Fan</div>
</div>
</div>
<div class='list_product'>
<div class='row'>
<div class='delete'>x</div>
<div class='title'>Standing Fan 2</div>
</div>
</div>
<div class='list_product'>
<div class='row'>
<div class='delete'>x</div>
<div class='title'>Standing Fan 3</div>
</div>
</div>
<div class='list_product'>
<div class='row'>
<div class='delete'>x</div>
<div class='title'>Standing Fan 4</div>
</div>
</div>
Jquery:
$('.delete').click(function() {
$(this).find('.list_product').remove();
});
Is not working. may i know why and how do i fix it? thanks
The closest() method returns the first ancestor of the selected element. An ancestor is a parent, grandparent, great-grandparent, and so on. The DOM tree: This method traverse upwards from the current element, all the way up to the document's root element (<html>), to find the first ancestor of DOM elements.
jQuery next() Method The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.
The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.
closest() The closest() method of the Element interface traverses the element and its parents (heading toward the document root) until it finds a node that matches the specified CSS selector.
Try this:
$(document).on('click', '.delete', function(e) {
e.preventDefault();
$(this).closest('.list_product').remove();
return false;
});
Just do $(this).closest('.list_product').remove()
.
API ref: http://api.jquery.com/closest/find
searches through the children of the current element. In this case, the .delete
elements don't have any children. Conversely, closest
goes up thru the DOM, looking for the first ancestor with the class list_product
. Hope this helps.
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