Jupiter
Jupiter

Reputation: 238

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.

Upvotes: 0

Views: 762

Answers (3)

zzzzBov
zzzzBov

Reputation: 179046

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).

Upvotes: 4

Martin
Martin

Reputation: 11041

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();

Upvotes: 0

Hari Pachuveetil
Hari Pachuveetil

Reputation: 10374

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

Upvotes: 1

Related Questions