user4962026
user4962026

Reputation:

Error: Cannot read property 'replaceChild' of undefined

I am trying to update a table to display the new row when I save a record. My code currently loads the entire table again along with the existing table. For example, I'm seeing rows 1-15, then I add a row and see 31 total rows, rows 1-15 and then rows 1-16 all in the same table.

Here is my code for the replace function which calls my original load function when it's time to replace the data. I based this off another example I saw.

function replaceData() {
    var old_tbody = document.getElementsByTagName('tbody');
    var new_tbody = document.createElement('tbody');
    loadData(new_tbody);
    old_tbody.parentNode.replaceChild(new_tbody,old_tbody);

    console.log("Data replaced");
}

I'm clearly not a JavaScript expert so any help would be appreciated.

Upvotes: 0

Views: 4391

Answers (2)

ymz
ymz

Reputation: 6914

getElementsByTagName function returns a HTML Collection (array-like object), that means that you have to specify which item of that array you want (even if there is only one item).

So your code basically should be:

var old_tbody = document.getElementsByTagName('tbody')[0];

Or you can use querySelector which returns only the first matched element. Like this:

var old_tbody = document.querySelector('tbody');

Upvotes: 1

Garett
Garett

Reputation: 16828

getElementsByTagName actually returns a collection of elements, so parentNode doesn't work. To get the actual DOM node you would do the following.

var old_tbody = document.getElementsByTagName('tbody')[0];

Upvotes: 0

Related Questions