Delete all table rows except one with a given class in javascript

1 year ago23k times

One can remove all table rows except one with a given class by using querySelectorAll to fetch all rows, then iterating through the NodeList and checking if the class matches the desired class. If it does not, then remove the row.


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

Add Answer

Add a codeAdd Code
Remove adsremove

Latest codes

view all

Latest Snippets

view all