Do usuwania poszczególnych wierszy w tabeli proponuję użyć Event Delegation
przykład
<style>
table {
width: 500px;
max-width: 500px;
}
th, td {
text-align: center;
font: 400 0.9em/1.1 system-ui;
padding: 0.25em 0.5em;
color: white;
}
th:first-child {
width: 1em;
max-width: 1em;
}
th:last-child {
width: 4em;
max-width: 4em;
}
th {
text-transform: capitalize;
font-variant: small-caps;
background-color: black;
}
tbody tr {
cursor: default;
transition:
background 0.5s,
opacity 0.8s 0.2s,
transform 1s cubic-bezier(0.5,-0.8,0.25,1.4);
}
tbody tr:nth-child(even) {
background-color: rgba(0,0,0,0.6);
}
tbody tr:nth-child(odd) {
background-color: rgba(0,0,0,0.5);
}
tbody tr:hover {
background-color: rgba(0,0,0,0.8);
}
tr.hide {
opacity: 0;
transform: scale(0);
}
</style>
<table id="words">
<thead>
<tr>
<th>id</th>
<th>question</th>
<th>answer</th>
<th>counter</th>
<th><!-- button --></th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
const words = [
{ id:1, question:'question1', answer: [ 'answer1.1', 'answer1.2', 'answer1.3' ], counter:2 },
{ id:2, question:'question2', answer: [ 'answer2.1', 'answer2.2', 'answer2.3' ], counter:3 },
{ id:3, question:'question3', answer: [ 'answer3.1', 'answer3.2', 'answer3.3' ], counter:1 },
{ id:4, question:'question4', answer: [ 'answer4.1', 'answer4.2', 'answer4.3' ], counter:2 }
]
window.onload = load;
function load() {
const tbody = document.querySelector('table#words tbody')
for (const word of words) {
const tr = document.createElement('TR');
tr.innerHTML = `<td>${word.id}</td>
<td>${word.question}</td>
<td>${word.answer}</td>
<td>${word.counter}</td>
<td><button class="btn btn-danger">Usuń</button></td>`;
tbody.appendChild(tr);
}
tbody.onclick = action;
function action({target}) {
if (target.nodeName == 'BUTTON' && target.classList.contains('btn-danger')) {
//console.log(target.closest('tr'));
target.closest('tr').classList.add('hide');
setTimeout(_=> { target.closest('tbody').removeChild(target.closest('tr')); }, 1000);
}
}
}
</script>
[ Element.closest() ] [ cubic-bezier ]