Search code examples
javascripthtml-tablerefreshinnerhtml

InnerHTML changes old variables


I'm doing a function that creates a table in JS. I create a variable table_row fill it and then add table_layout.appendChild(table_row); it to the table_layout element. Next, I clean it table_row through innerHTML='', but when cleaning, the variable that I ALREADY added to the element table_layout is also cleared.


Why is this happening? Should the added element be cleared? How can this be avoided? Look at the CODE.

var columns = ["col1", "col2", "col3"];
var rows = 5;

function Table() {
  var table_layout = document.createElement("table");
  var table_row = document.createElement("tr");

  for (var i = 0; i < columns.length; i++) {
    // main row
    table_row.innerHTML += "<th>" + columns[i] + "</th>";
  }

  table_layout.appendChild(table_row); //add in table element

  // table_row.innerHTML = ""; //If you uncomment this line, then we get an empty output!
  
  //refresh table_row html, that would generate a new line
  //But when cleaning. Cleared in the previously added item in table_layout .... how??

  
  
  // 		 for (var j = 0; i < columns.length; j++) {
  // 		 		table_main_row.innerHTML += '<td></td>';
  // 		 	}

  // 		 for (var i = 0; i < rows; i++) {
  // 		 	table_layout.appendChild(table_row);
  // 		 }

  return table_layout;
}

var div = document.getElementById("qqq");
div.appendChild(Table());
#qqq {
  background: red;
}
<div id="qqq"></div>


Solution

  • The table_row variable contains a reference. You will need to create a new element for each row.

    // creates a DOM Element and saves a reference to it in the table_row variable
    var table_row = document.createElement("tr");
    
    // updates the DOM Element through the reference in the table_row variable
    table_row.innerHTML += "<th>" + columns[i] + "</th>";
    
    // still references the DOM Element, so you are clearing its content
    // table_row.innerHTML = "";
    

    You will need to . . .

    // create a new DOM Element to use
    table_row = document.createElement("tr");
    // then update its contents
    table_main_row.innerHTML += '<td></td>';
    

    . . . for each iteration.

    See JavaScript on MDN for tutorials, references, and more.