Mitch
Mitch

Reputation: 45

Remove Table Row by Class Name - Javascript

I've looked through so many forum posts about this simple piece of code. And tried many variations and methods with nothing working.

I have a script that builds a table based on a database query. I limit it to 10 results and provide forward and back buttons to go to other results from the database. When you press the next button, I need it to delete all the current table rows so it can recreate them with the new results of the query. I am using the following code to remove the rows;

if (document.getElementsByClassName('shiftTrRow')) {
    table = document.getElementById('resultsTable')
    deleteRow = document.getElementsByClassName('shiftTrRow');
    table.removeChild(deleteRow);       
}

I use the if case to check if there are any rows to delete, I've added an alert to test if there are rows discovered and this works.

When I run the code I receive the following error on the line:

table.removeChild(deleteRow)

Uncaught Error: NOT_FOUND_ERR: DOM Exception 8 

I've looked up the error code and it explains that the element couldn't be found, but this cannot be the case since this code will only execute if the element is found. If anyone knows what I'm doing wrong or a better way to do this I would really appreciate it.

Upvotes: 2

Views: 6433

Answers (3)

Bergi
Bergi

Reputation: 664620

document.getElementsByClassName('shiftTrRow')
                   ^

returns a NodeList, i.e. an array of elements. You will need to loop over them and remove every of them on its own (but watch out, the collection is live and will shrink while you remove the elements).

Also, the getElementsByClassName may return elements that are no rows of that table at all, resulting in the NOT FOUND exception you receive.

However, the simplest way to remove rows from a table is its deleteRow method:

var table = document.getElementById('resultsTable');
while (table.rows.length > 0)
    table.deleteRow(0);

Upvotes: 1

Zeta
Zeta

Reputation: 105885

document.getElementsByClassName will return a NodeList, not a single node. You'll need to chose a node from that list, for example document.getElementsByClassName('shiftTrRow')[0].

Also make sure that the node is actually a child of the given table. The following code is a little bit more exception safe:

if (document.getElementsByClassName('shiftTrRow'))
{    
    deleteRow = document.getElementsByClassName('shiftTrRow')[0];

    if(deleteRow.parentNode)
        deleteRow.parentNode.removeChild(deleteRow);
}

Upvotes: 2

Brian Ustas
Brian Ustas

Reputation: 65539

document.getElementsByClassName returns an array of elements. table.removeChild expects a DOM element, not an array, for its argument.

Upvotes: 1

Related Questions