Skip to content Skip to sidebar Skip to footer

Dynamically Update Table Cells Pure Javascript

I have the following code body = document.body; tbl = document.createElement('table'); tbl.setAttribute('id','tab'); document.body.style.background = 'rgba(0, 0, 0, 0.4)' tbl.con

Solution 1:

Solution was very simple: it should be innerHTML

Some code optimizations for free:

//moved the body background to CSS//this is fine, create a table with createElement
tbl = document.createElement('table');
tbl.setAttribute('id', 'tab');
tbl.className = "progress";
//moved table style to css


txt = ['Transfer Status', 'File name:', 'Bytes Transferred:', '% Transferred:'];


for (var i = 0; i < 4; i++) {

  //create a div in every loopvar divContainer = document.createElement('div');
  //give it a classname
  divContainer.className = 'container';

  var tr = tbl.insertRow();
  var td = tr.insertCell();
  td.appendChild(document.createTextNode(txt[i]));

  //append the div
  td.appendChild(divContainer);
}

document.body.appendChild(tbl);

functionupdate() {
  var table = document.getElementById('tab');
  //tr selection is unnecessaryvar tds = table.querySelectorAll('tr:not(:first-child) > td'); //querySelector is more modern - select all tds except the first - which describes the table content and should not be updated.var vl = [CurrentFileName, BytesTransferredThisFile + ' of ' + TotalBytesThisFile, strPerc_1];

Array.prototype.forEach.call(tds, function(element, index) {

    element.querySelector('.container').textContent = vl[index];
  });



}

//simulation:var files = {
  "currentFileName": "test1",
  "BytesTransferredThisFile": 0,
  "TotalBytesThisFile": 10240,
  "strPerc_1": 0
};

timer = setInterval(function() {
  files.BytesTransferredThisFile += 1000;
  CurrentFileName = files.currentFileName;
  BytesTransferredThisFile = files.BytesTransferredThisFile;
  TotalBytesThisFile = files.TotalBytesThisFile;
  strPerc_1 = (files.BytesTransferredThisFile / files.TotalBytesThisFile * 100).toFixed(1);

  if (files.BytesTransferredThisFile <= files.TotalBytesThisFile) {
    update();
  } else {
    clearInterval(timer)
  }


}, 1000);
body {
  background: rgba(0, 0, 0, 0.4);
}

table.progress {
  border: 1px solid white;
  background-color: #ffffff;
  width: 25%;
  margin-bottom: 1300px;
  margin-left: 500px;
  transform: translateY(50%);
}

Post a Comment for "Dynamically Update Table Cells Pure Javascript"