Search code examples
javascripthtmlrows

Using JS to add rows but adds beside rather than below


I am trying to add information to a table but it adds it beside the table row expanding it rather than adding it below it. I have tried adding breaks and other table rows below it, but it simply ignores them and still adds on to the first row. The information being stored is correct, it just won't go to the right position.

Here is the HTML with the original table row Table before adding Table after adding `

        <table>
            <tr>
                <td class="tbl-hdr">Player 1</td>
                <td class="tbl-hdr">Player 1 Team</td>
                <td class="tbl-hdr">Player 2 Team</td>
                <td class="tbl-hdr">Player 2</td>
                <td class="tbl-hdr date">Date + VOD</td>
            </tr>
        </table>

Here is the relevant JS `

let template = `
            <tr>
                <td>${name1}</td>
                <td>${name2}</td>
                <td>${team1}</td>
                <td>${team2}</td>
                <td>${date}</td>
                <td>${VOD}</td>
            </tr>`;
table.innerHTML += template;

Solution

  • Solution

    Use .insertRow(-1) to insert row below exist row on table then use .innerHTML to append content.

    let name1="A", name2="B", team1="C", team2="team2", date="date", VOD="VOD"
    let template = `
                <tr>
                    <td>${name1}</td>
                    <td>${name2}</td>
                    <td>${team1}</td>
                    <td>${team2}</td>
                    <td>${date}</td>
                    <td>${VOD}</td>
                </tr>`;
                
    var table = document.querySelector("table")
    var row = table.insertRow(-1);
    row.innerHTML += template;
    <table>
                <tr>
                    <td class="tbl-hdr">Player 1</td>
                    <td class="tbl-hdr">Player 1 Team</td>
                    <td class="tbl-hdr">Player 2 Team</td>
                    <td class="tbl-hdr">Player 2</td>
                    <td class="tbl-hdr date">Date + VOD</td>
                </tr>
            </table>