Search code examples
javascripthtmlnodesappendchildremovechild

In-place replacement of HTML Elements


I have table that I generate with the following js:

var tbl = document.createElement('table');
var tbdy = document.createElement('tbody');
var thd = document.createElement('thead');

var Headings = ["Lun","File","CDROM","Removable","ReadOnly","NoFUA"];
var tr = document.createElement('tr');
for (var i = 0; i < Headings.length; i++) {
    var td = document.createElement('td');
    td.appendChild(document.createTextNode(Headings[i]))
    tr.appendChild(td);
}
thd.appendChild(tr);

for (var lun in data) {
    console.log(lun);
    var tr = document.createElement('tr');
    tr.appendChild(document.createElement('td').appendChild(document.createTextNode(lun)));

    for (var info in data[lun]) {
        var td = document.createElement('td');
        td.appendChild(document.createTextNode(data[lun][info]))
        tr.appendChild(td)
    }
    tbdy.appendChild(tr);
}
tbl.appendChild(thd);
tbl.appendChild(tbdy);
var table = document.getElementById('file-table');

and the following relevant HTML:

<table id="file-table" style="width:100%"></table>

the appendChild method you see in the last line of the js works however the intent of the creating the table in with the js is to do a complete replacement of all childNodes of 'file-table'.

I have tried iterating over the childNodes and using the removeChild method but this yields some interesting results - won't completely remove all nodes or sometimes an error message about the first parameter not being a Node.

Any ideas?


Solution

  • Could you select the target elements, and update them directly?

    document.getElementById('td1').innerHTML = "Some text to enter"
    

    If not, you could also replace the table body itself:

    var new_tbody = document.createElement('tbody');
    populate_with_new_rows(new_tbody);
    old_tbody.parentNode.replaceChild(new_tbody, old_tbody)