简体   繁体   English

错误:无法读取未定义的属性“ replaceChild”

[英]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. 例如,我看到的是第1-15行,然后添加一行并看到总共31个行,第1-15行,然后是1-16行都在同一张表中。

Here is my code for the replace function which calls my original load function when it's time to replace the data. 这是我的replace函数的代码,该代码在需要替换数据时调用我的原始load函数。 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. 我显然不是JavaScript专家,因此不胜感激。

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). getElementsByTagName函数返回一个HTML集合 (类似于数组的对象),这意味着您必须指定所需的数组中的哪一项(即使只有一项)。

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. 或者,您可以使用querySelector仅返回第一个匹配的元素。 Like this: 像这样:

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

getElementsByTagName actually returns a collection of elements, so parentNode doesn't work. getElementsByTagName实际上返回元素的集合,因此parentNode不起作用。 To get the actual DOM node you would do the following. 要获取实际的DOM节点,请执行以下操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM