agregar una fila a una tabla html in javascript

You can use JavaScript to dynamically add a row to an HTML table. Here's an example code:

<table id="myTable">
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>John</td>
            <td>30</td>
        </tr>
        <tr>
            <td>Jane</td>
            <td>25</td>
        </tr>
    </tbody>
</table>

<button onclick="addRow()">Add Row</button>

<script>
    function addRow(){
        var table = document.getElementById("myTable");
        var row = table.insertRow();
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        cell1.innerHTML = "New Name";
        cell2.innerHTML = "New Age";
    }
</script>
652 chars
32 lines

Here, we're using the insertRow() method to add a new row to the table and the insertCell() method to add two cells to that row. Finally, we're setting the content of those cells using the innerHTML property.

Note: The onclick attribute is just for demonstration purposes. In real-world scenarios, you should be using event listeners instead.

related categories

gistlibby LogSnag