I have a table where I'm dynamically appending and removing rows. When pressing 'remove' I want to remove the whole row. This works cleanly with the already existing rows, but when using the same function for the new rows it removes everything.
How can I remove just the newly created rows, not all rows?
I have tried using find() to find the tr but it doesn't work.
$("#addRow").click(function() {
$("#table").append(
`<tr>`,
`<td></td>`,
`<td></td>`,
`<td></td>`,
`<td></td>`,
`<td></td>`,
`<td class="remove"><button>Remove</button></td>`,
`</tr>`
);
$('.remove button').on('click', function() {
removeRow($(this))
});
})
$('.remove button').on('click', function() {
removeRow($(this))
});
function removeRow(row) {
row.parent().parent().remove();
}
#table {
width: 80%;
margin-left: auto;
margin-right: auto;
}
#table td {
width: 20%;
border: solid 1px black;
}
#table .remove {
border: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td class="remove"><button>Remove</button></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td class="remove"><button>Remove</button></td>
</tr>
</table>
<p><button id="addRow">Add a new row</button></p>