Add and count new row with js
Here are a few ways to add and count new rows with JavaScript:
Method 1: Using innerHTML
const table = document.getElementById('myTable');
const newRow = document.createElement('tr');
newRow.innerHTML = '<td>New Row</td><td>New Row</td>';
table.appendChild(newRow);
const rowCount = table.rows.length;
console.log(`New row count: ${rowCount}`);
This method creates a new <tr>
element and sets its innerHTML to a new row with two <td>
elements. Then, it appends the new row to the table using appendChild
. Finally, it logs the new row count to the console.
Method 2: Using insertRow
const table = document.getElementById('myTable');
const newRow = table.insertRow();
const cell1 = newRow.insertCell();
const cell2 = newRow.insertCell();
cell1.innerHTML = 'New Row';
cell2.innerHTML = 'New Row';
const rowCount = table.rows.length;
console.log(`New row count: ${rowCount}`);
This method creates a new row using insertRow
and then inserts two new cells using insertCell
. Then, it sets the innerHTML of each cell to a new row. Finally, it logs the new row count to the console.
Method 3: Using a loop
const table = document.getElementById('myTable');
for (let i = 0; i < 1; i++) {
const newRow = document.createElement('tr');
for (let j = 0; j < 2; j++) {
const newCell = document.createElement('td');
newCell.innerHTML = `New Row ${j}`;
newRow.appendChild(newCell);
}
table.appendChild(newRow);
}
const rowCount = table.rows.length;
console.log(`New row count: ${rowCount}`);
This method creates a new row using a loop and then inserts two new cells using another loop. Then, it sets the innerHTML of each cell to a new row. Finally, it logs the new row count to the console.
In all cases, the rowCount
variable will hold the new row count, which you can use to update your UI or perform further actions.