Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript is adding <tr>s to my table elements automatically

As you can see from this screenshot:

enter image description here

each element is being put into its own tr.

I do not want that, I just want each element to be in a td then surround everything with one tr

HTML:

<div id='result'>
    <table class='table'>
        <thead>
            <tr><th>Question</th><th>Animal</th><th>Expected</th><th>You Picked</th><th>Result</th></tr>
        </thead>
        <tbody id='result-table'>
        </tbody>
    </table>
</div>

Javascript:

function displayResult() {
    let tableDisplay = document.getElementById("result-table")
    let theResult = document.getElementById("result")
    theResult.style.display = "block"

    for(let i = 0; i<qArr.length; i++){
        tableDisplay.innerHTML = tableDisplay.innerHTML + `<td>` + qArr[i] + `</td>`
    }
    // qArr.forEach(x => {
    //     tableDisplay.innerHTML = tableDisplay.innerHTML + `<td>` + x + `</td>`
    // })

}
like image 939
Ali Avatar asked Mar 02 '26 10:03

Ali


1 Answers

td can't be children for tbody, only for tr. Because browser independently add this element. You need data to result-row.

<tbody id='result-table'>
    <tr id='result-row'></tr>
</tbody>

By the way, interaction with the DOM is an expensive operation. First it’s better to form an array and then insert once.

like image 63
Alexander Avatar answered Mar 04 '26 01:03

Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!