Elements <td> in a new row when reaching a certain quantity

Asked

Viewed 20 times

0

I have a code in which it aims to generate some elements <td> (cells) in the table and if the row containing the elements <td> achieve a certain amount of elements <td> (in which is 10) a new line is created with the element tr and inserts the rest of the elements <td> in this new line, if you re-shoot 10 elements <td> is repeated all over again:

let table = document.querySelector('table');

// Criar inicialmente o elemento tr.
let tr = document.createElement('tr');

table.appendChild(tr);

// Gerar 20 elementos td para extrapolar a quantidade máxima.
for (let t = 1; t <= 20; t ++) {
    let td = document.createElement('td');

    // Inserir o conteúdo do incremento no td.
    td.innerHTML = t;

    let trChild = document.querySelector('tr');

    // Verificar se o número de filhos é maior do que 10.
    // Se sim criar um novo elemento tr e inserir os td.
    if (trChild.childElementCount > 10) {
        tr = document.createElement('tr');
        tr.appendChild(td);
    }

    else {
        // Se não continuar no tr atual.
        tr.appendChild(td);
    }
}
table, td {
    border: 1px solid #505050;
    border-collapse: collapse;
    padding: 10px;
    font-family: sans-serif;
    font-size: 1.1em;
}
<table>

</table>

But I see that my logic is kind of wrong, where I’m going wrong and what I can do to fix?

1 answer

2


You forget to tuck it into the table when it is created, and the count also goes wrong on account of the operator > which only returns true when there are already 1, so correct is < 11 or == 10.

let table = document.querySelector('table');

// Criar inicialmente o elemento tr.
let tr = document.createElement('tr');

table.appendChild(tr);

// Gerar 20 elementos td para extrapolar a quantidade máxima.
for (let t = 1; t <= 20; t ++) {
    let td = document.createElement('td');

    // Inserir o conteúdo do incremento no td.
    td.innerHTML = t;

    // Verificar se o número de filhos é maior do que 10.
    // Se sim criar um novo elemento tr e inserir os td.
    if (tr.childElementCount == 10) {
        tr = document.createElement('tr');
        table.appendChild(tr);
    }
    // adiciona na nova referencia do tr
    tr.appendChild(td);
}
table, td {
    border: 1px solid #505050;
    border-collapse: collapse;
    padding: 10px;
    font-family: sans-serif;
    font-size: 1.1em;
}
<table>

</table>

I hope I’ve helped :)

  • Thanks, my buddy was this msm :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.