Reputation: 5256
I have a table rendered dynamically. There's one <tr class="dolly">
somewhere inside its <tbody>
that serves as a reference row - it gets cloned and filled with data later. I need to delete all rows except that one.
for
loop: uses an increment which quickly gets invalid as the rows are deletedwhile
loop: continues until all rows are deleted, which never happens because of the conditionPlease let me know if you have any ideas. Please no jQuery.
Upvotes: 1
Views: 1067
Reputation: 21
Here is my solution for this question.
// Fetch all rows
const rows = document.querySelectorAll('tr');
// Iterate through the rows and remove those that do not have the desired
class
const className = 'class-name';
rows.forEach(row => {
if (!row.classList.contains(className)) {
row.remove();
}
});
I took refernce from here - https://bbbootstrap.com/code/delete-all-table-rows-except-one-given-class-javascript-61232938
Upvotes: 0
Reputation: 2140
I am gonna share my solution here.
function deleteAllOtherRowExceptOne(exceptionIndex) {
const tableBody = document.querySelector('#my-table-tbody')
const tableBodyRowLength = tableBody.rows.length
let deleteIndex = 0
for (let i = 0; i < tableBodyRowLength; i++) {
if(i == exceptionIndex){
deleteIndex++
} else {
tableBody.deleteRow(deleteIndex)
}
}
}
Upvotes: 0
Reputation: 7891
use document.querySelectorAll('tr:not(.dolly)')
to select all tr's
except with class .dolly
and then iterate over it to remove the filtered tr's
.
document.querySelectorAll('table tr:not(.dolly)').forEach((tr) => {
tr.remove();
});
<table>
<tr class="dolly">
<td>One</td>
</tr>
<tr>
<td>Two</td>
</tr>
<tr>
<td>Three</td>
</tr>
</table>
Upvotes: 2