1

estoy intentando crear una tabla manipulando el DOM con JS, mi objetivo es una tabla con una fila horizontal con las letras del abecedario y otra vertical con números mientras las demás celdas estan en blanco.

Algo así (perdón por mi arte con el paint): introducir la descripción de la imagen aquí

He llegado a crear las celdas con los números y las letras con bucles for, aunque la colocación de la columna de los números me esta trayendo de cabeza con un display grid consigo darle la colocación que quiero, aunque sé que no es la manera ideal.

El problema son las celdas centrales. No consigo colocarlas en posición y creo que he llegado a un punto donde me estoy complicando demasiado cuando seguro que hay una solución más sencilla.

Este es mi código:

window.onload = function() {
    // Get the first element in the body
    var body = document.getElementsByTagName('body')[0];

    // Create a table
    var table = document.createElement('TABLE');
    

//! ********************************************************

    // Create a table-head
    var abecedary = [' ','A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    var tableHead = document.createElement('THEAD');
    
    // Append the table head to the table
    table.appendChild(tableHead);
    
    var trA = document.createElement('TR');
    trA.setAttribute('class', 'abecedaryTR');
    // Append the rows to the head
    tableHead.appendChild(trA);
    
    for (var i = 0; i < abecedary.length; i++) {
        // Create the rows
        var th = document.createElement('TH');
        th.setAttribute('class', 'abecedaryTH');
        th.innerHTML = abecedary[i];
        // Append them to the rows
        trA.appendChild(th);
    }


//! ********************************************************

    // Create a table-body
    var tableBody = document.createElement('TBODY');
    
    // Append the table body to the table
    table.appendChild(tableBody);

    

    // Create the rows
    var trL = document.createElement('TR');
    trL.setAttribute('class', 'lettersTR');
    // Append the rows to the body
    tableBody.appendChild(trL);
    // Loop to create the cells and rows
    for (var i = 1; i <= 13; i++) {
        
        var td = document.createElement('TD');
        td.setAttribute('class', 'lettersTD');
        td.innerHTML = i;
        // Append them to the rows
        trL.appendChild(td);
    }

    // Loop to create the cells and rows
    for (var i = 0; i < 13; i++) {
        // Create the rows
        var tr = document.createElement('TR');
        // Append the rows to the body
        tableBody.appendChild(tr);

        // Create the cells
        for (var j = 0; j < 16; j++){
            var td = document.createElement('TD');
            td.setAttribute('contenteditable', 'true');
            // Append them to the rows
            tr.appendChild(td);
        }
    }
    // Append the table to the body
    body.appendChild(table);
}
* {
    margin: 0;
    padding: 0;
}

h1 {
    text-align: center;
} 

.lettersTR {
    display: grid;
}

table th {
    padding: 0.5em;
    border: 1px solid tomato;
} 
 
table td {
    padding: 0.5em;
    border: 1px solid tomato;
} 

table td:hover {
    background-color: violet;
} 

table td:focus {
    background-color: grey;
}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Spreadsheet</title>
</head>
<body>
    <script src="index.js"></script>
</body>
</html>

2 respuestas 2

0

Tu código iba bien, excepto porque te sobra un ciclo, donde creas las filas con solo una celda para colocar el número:

// Create the rows
var trL = document.createElement('TR');
trL.setAttribute('class', 'lettersTR');
// Append the rows to the body
tableBody.appendChild(trL);
// Loop to create the cells and rows
for (var i = 1; i <= 13; i++) {
    
    var td = document.createElement('TD');
    td.setAttribute('class', 'lettersTD');
    td.innerHTML = i;
    // Append them to the rows
    trL.appendChild(td);
}

Después tienes ciclo donde vuelves a agregar filas e intentas "agregar las celdas faltantes", pero deberías tomar las filas que creaste anteriormente.

Para no duplicar códigos, se debe hacer todo en el segundo ciclo, con los siguientes pasos:

  • Eliminar el ciclo mencionado arriba
  • Recorrer desde 0 hasta la cantidad de elementos en abecedary (Tenías hasta 16)
  • Cuando es la primera celda (j == 0) se debe asignar solo el número de fila y asignar clase
  • Para el resto de celdas se aplica el estilo para tener contenido editable

window.onload = function() {
    // Get the first element in the body
    var body = document.getElementsByTagName('body')[0];

    // Create a table
    var table = document.createElement('TABLE');
    

    // Create a table-head
    var abecedary = [' ','A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    var tableHead = document.createElement('THEAD');
    
    // Append the table head to the table
    table.appendChild(tableHead);
    
    var trA = document.createElement('TR');
    trA.setAttribute('class', 'abecedaryTR');
    // Append the rows to the head
    tableHead.appendChild(trA);
    
    // Agregar celdas al encabezado
    for (var i = 0; i < abecedary.length; i++) {
        // Create the rows
        var th = document.createElement('TH');
        th.setAttribute('class', 'abecedaryTH');
        th.innerHTML = abecedary[i];
        // Append them to the rows
        trA.appendChild(th);
    }

    // Create a table-body
    var tableBody = document.createElement('TBODY');
    
    // Append the table body to the table
    table.appendChild(tableBody);

    // ******** Se eliminó el ciclo que solo creaba cada fila con una celda *****

    // Loop to create the cells and rows
    for (var i = 0; i < 13; i++) {
        // Create the rows
        var tr = document.createElement('TR');
        // Append the rows to the body
        tableBody.appendChild(tr);

        // Agregar celdas a la fila, con base en cantidad de letras
        for (var j = 0; j < abecedary.length; j++){
            var td = document.createElement('TD');
            if(j == 0) {
                // Es la primera columna, colocar número de fila
                td.innerText = i + 1;
                // Agregar clase que corresponde
                td.setAttribute('class', 'lettersTD');
            } else {
                td.setAttribute('contenteditable', 'true');
            }
            // Append them to the rows
            tr.appendChild(td);
        }
    }
    // Append the table to the body
    body.appendChild(table);
}
* {
    margin: 0;
    padding: 0;
}

h1 {
    text-align: center;
} 

.lettersTR {
    display: grid;
}

table th {
    padding: 0.5em;
    border: 1px solid tomato;
} 
 
table td {
    padding: 0.5em;
    border: 1px solid tomato;
} 

table td:hover {
    background-color: violet;
} 

table td:focus {
    background-color: grey;
}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Spreadsheet</title>
</head>
<body>
    <script src="index.js"></script>
</body>
</html>

0

Quizás esto te ayude:

 window.onload = function () {
        var body = document.getElementsByTagName('body')[0];
        var table = document.createElement('table');
        var abecedary = [' ', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
            'R', 'S',
            'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
        ];
        var rows = 13;
        var len_abecedary = abecedary.length;
        var tableHead = document.createElement('thead');

        for (let i = 0; i <= rows; i++) {
            var tr = null;
            if (i != 0) {
                tr = document.createElement('tr');
            }
            for (let j = 0; j < len_abecedary; j++) {
                var td = document.createElement('td');
                if (i == 0) {
                    td.innerText = abecedary[j];
                    tableHead.appendChild(td);
                } else if (j == 0) {
                    td.innerText = i;
                    tr.appendChild(td);
                } else {
                    td.innerText = null;
                    tr.appendChild(td);
                }
            }
            if (tr) {
                table.appendChild(tr);
            }
        }
        table.appendChild(tableHead);
        body.appendChild(table);
    }

Estas dos imágenes muestran el resultado: introducir la descripción de la imagen aquí

introducir la descripción de la imagen aquí

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.