Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery find nearest class and remove it

Tags:

jquery

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

like image 891
user1594367 Avatar asked Aug 14 '12 13:08

user1594367


People also ask

How do I get the closest div using jQuery?

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.

How can I get next sibling in jQuery?

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.

How do I find a specific parent in jQuery?

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.

What is closest method in Javascript?

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.


2 Answers

Try this:

$(document).on('click', '.delete', function(e) {
   e.preventDefault();
   $(this).closest('.list_product').remove();
   return false;
});
like image 133
mmcachran Avatar answered Nov 16 '22 00:11

mmcachran


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.

like image 28
Abraham Avatar answered Nov 16 '22 00:11

Abraham