简体   繁体   中英

Remove parent element and all children

So I have a table, and every time the button gets submitted it adds a row to the table with 4 columns, I place a delete button in each row. My purpose is to be able to delete the entire row, but when I press it it only deletes the button. How can I delete the entire row?

$(this).parent().remove()

I tried this but it doesn't work, the td is directly within the tr so it should access the tr and delete it but the row still exists.

You want to select the closest tr element, not the immediate parent. Without seeing your event binding, I'd guess that $(this) is the button, and that $(this).parent() is the <td> . Instead you should try:

$(this).closest('tr').remove();

Or, if you can guarantee a specific hierarchy of tr>td>button , then you could use:

$(this).parent().parent().remove();

I strongly discourage using the latter format, as it is tightly coupled to the structure of the HTML. If your HTML starts out as:

<tr>
    <td>
        <button>Example</button>
    </td>
</tr>

and later changes to:

<tr>
    <td>
        <div class="wrapper">
            <button>Example</button>
        </div>
    </td>
</tr>

using closest('tr') will continue to work, but using parent().parent() will break.


Relating to your secondary issue of not having events fired. If you're binding events with $('.foo button').click(removeRow); (where .foo matches the table element), the events won't apply to newly created button elements. Instead you should be using the event-delegation form of on (or simply delegate if you're using an older version of jQuery):

$('.foo').on('click', 'button', removeRow);

This would store the event binding on the table element, and when the callback gets called, it would check to see if the element that triggered the specified event matches the selector specified in the second argument (in this case 'button' ) if it matches, it triggers the specified handler (in this case removeRow ) in with the matched element as the context (within the handler, this would still point to a button element).

  $(this).closest('tr').remove();

I am assuming your code looks like this:

<table>
    <tr>
        <td>Column</td>
        <td><button></button></td>
    </tr>
</table>

So, your $(this).parent() is the <td> , not the <tr> . You need another parent() :

$(this).parent().parent().remove();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM