cubefox
cubefox

Reputation: 1301

Update an element created via appendChild

I created a table on my document using: document.body.appendChild(table)

now every time I make a change on my table I want to run

document.body.removeChild(table)
document.body.appendChild(table)

so that the content of the table on my page is updated. This does however not work in the first place as I get

app.js:75 Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

as an error message, and it also seems like a really clunky solution to the problem.

Upvotes: 0

Views: 1346

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075925

now every time I make a change on my table I want to run...so that the content of the table on my page is updated

There's no need to do that. Just modify the table. It's an object in the DOM; modifications to it are rendered by the browser. This is fundamental to how the DOM works.

var table = document.createElement("table");
var tbody = document.createElement("tbody");
table.appendChild(tbody);
document.body.appendChild(table);
var timer = setInterval(function() {
    // This modifies the existing table
    tbody.insertAdjacentHTML(
        "beforeend",
        "<tr><td>" + tbody.children.length + "</td></tr>"
    );
    if (tbody.children.length == 5) {
        clearInterval(timer);
    }
}, 500);

Upvotes: 1

vijay krishna
vijay krishna

Reputation: 524

Your appended table is returned by appendChild. You can use it to modify in future.

Upvotes: 0

Related Questions