用replaceChild函数替换<div>的第一个子节点

时间:2017-03-24 04:47:18

标签: javascript

我正在使用JavaScript编写简单的表生成器。我写了函数createChild()就像这样:

function createTable(row_count, column_count) {
    var table = document.createElement("table"); 

    for (row = 0; row < row_count; row++) {
        let tr = document.createElement("tr");
        for (column = 0; column < column_count; column++) {
            let td = document.createElement("td"); 
            td.innerHTML = "a<sub>(" + (row+1) + "," + (column+1) + ")</sub>";
            tr.appendChild(td);
        }
        table.appendChild(tr);
    }
    table.setAttribute("border", "1");

    var tableHolder = document.getElementById("table-container");
    var oldTable = tableHolder.firstChild;
    if (!oldTable) {
        tableHolder.appendChild(table);
    }
    else {
        tableHolder.firstChild.replaceWith(table);
        //tableHolder.replaceChild(tableHolder.firstChild, table);
    }
}

问题出现在以下几行:

tableHolder.firstChild.replaceWith(table);
//tableHolder.replaceChild(tableHolder.firstChild, table);

如果我使用第一行,它可以正常工作,但当我将其切换到第二行时,它不能用于错误Uncaught DOMException: Failed to execute 'replaceChild' on 'Node': The node to be replaced is not a child of this node.

我无法弄清楚出了什么问题..请帮忙。

2 个答案:

答案 0 :(得分:0)

您不小心将传递给Node#replaceChild的参数的顺序切换了。要插入的节点位于要替换的节点之前,有点违反直觉:

tableHolder.replaceChild(table, tableHolder.firstChild);

演示片段:

function createTable(row_count, column_count) {
    var table = document.createElement("table"); 

    for (row = 0; row < row_count; row++) {
        let tr = document.createElement("tr");
        for (column = 0; column < column_count; column++) {
            let td = document.createElement("td"); 
            td.innerHTML = "a<sub>(" + (row+1) + "," + (column+1) + ")</sub>";
            tr.appendChild(td);
        }
        table.appendChild(tr);
    }
    table.setAttribute("border", "1");

    var tableHolder = document.getElementById("table-container");
    var oldTable = tableHolder.firstChild;
    if (!oldTable) {
        tableHolder.appendChild(table);
    }
    else {
        //tableHolder.firstChild.replaceWith(table);
        tableHolder.replaceChild(table, tableHolder.firstChild);
    }
}

createTable(10, 10)
<div id="table-container"></div>

答案 1 :(得分:0)

请检查更新的fiddler.there有替换Child的更新。

http://jsfiddle.net/HB7LU/28302/

在这里输入代码

    tableHolder.replaceChild(table, tableHolder.firstChild);