Problem with table in JavaScript

0

I have a problem generating a table by JavaScript, in the code that I show below, the rows are generated on the right instead of continuing below to follow the column, the first column and the first row have to have & lt ; 'th' > as a requirement and the other cells < 'td' >.

Is it possible to develop the table like this through JavaScript?

function genera_tabla() {
 
  var body = document.getElementsByTagName("body")[0];
  var tabla   = document.createElement("table");
  var tblBody = document.createElement("tbody");
 
  for (var i = 0; i < 4; i++) {
    
    var hilera = document.createElement("th");
 
    for (var j = 0; j < 4; j++) {

      var celda = document.createElement("td");
      var textoCelda = document.createTextNode("fila "+i+", columna "+j + "\n");
      celda.appendChild(textoCelda);
      hilera.appendChild(celda);
    }

    tblBody.appendChild(hilera);
  }
	
  tabla.appendChild(tblBody);

  body.appendChild(tabla);
	
  tabla.setAttribute("border", "2");
}
<html>
	
<input type="button" value="Genera una tabla" onclick="genera_tabla()">
	
</html>
    
asked by InThaHouse 13.10.2018 в 16:02
source

2 answers

2

The error: var hilera = document.createElement("tr"); instead of var hilera = document.createElement("th");

Pata create cells th I've used

let elmt = (j == 0 || i == 0) ? "th" : "td";
var celda = document.createElement(elmt);

function genera_tabla() {
  var body = document.getElementsByTagName("body")[0];
  var tabla = document.createElement("table");
  var tblBody = document.createElement("tbody");

  for (var i = 0; i < 4; i++) {
    var hilera = document.createElement("tr");

    for (var j = 0; j < 4; j++) {
      let elmt = (j == 0 || i == 0) ? "th" : "td";
      var celda = document.createElement(elmt);
      var textoCelda = "fila " + i + ", columna " + j + "\n";
      celda.textContent = textoCelda;
      hilera.appendChild(celda);
    }

    tblBody.appendChild(hilera);
  }

  tabla.appendChild(tblBody);

  body.appendChild(tabla);

  tabla.setAttribute("border", "2");
}
<html>
	
<input type="button" value="Genera una tabla" onclick="genera_tabla()">
	
</html>
    
answered by 13.10.2018 / 16:27
source
0

You are using a th where a tr must go, only that change is already in table format.

Keep in mind that th are cells for titles and td are cells for content, in other words you are entering a cell in another cell and not a cell in a row

The row with the titles (th) should not be part of the for that fills the table

    
answered by 13.10.2018 в 16:40