Adding rows and columns in DOM table

Asked

Viewed 87 times

0

I’m having difficulty using DOM to generate an HTML table. Follow my code.

function table(){
let max=100;
let table = document.getElementById('tableNumber');

    table.innerHTML += '<tr>';


    for (let i=1; i<=max; i++){
        table.innerHTML += '<td> '+i+' </td>'; 
        if (i%10 == 0) {
            table.innerHTML += '</tr>';
        }
    }
}    

Since he’s not closing the line when the rest of i for 10 to 0, what I’m doing wrong?

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

3

Shall we do it the proper way? Writing in the DOM is gambiarra, we will manipulate it as it should be (anyway had logic errors in the original code).

function table() {
    let max = 100;
    let table = document.getElementById('tableNumber');
    let linha;
    for (let i = 0; i < max; i++) {
        if (i % 10 == 0) linha = table.insertRow();
        linha.insertCell().appendChild(document.createTextNode(i + 1));
    }
}
table();
<table id = "tableNumber"></table>

I put in the Github for future reference.

Documentation: insertRow(), insertCell(), createTextNode().

Browser other questions tagged

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