I want to add a table row to a table each time you click on an element. The added table row should have an ID. But the ID doesn't appears in the browser.
function add() {
document.getElementById("tbody").insertRow().innerHTML = `
<tr id="tablerow"> <!-- The ID don't work -->
<td>
Table row
</td>
</tr>
`;
}
#add {
cursor: pointer;
}
#tablerow {
background: #f00;
}
<table>
<thead>
<tr>
<th>Table Head</th>
<th></th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
<a onclick="add()" id="add">Click to add a table row</a>
Use
+=instead of.insertRow():Note:
Ids in HTML are unique, and that's why I've made a counter and attached it to Id to not repeat id for many elements which are not good, otherwise useclass='tablerow'Another note:
addEventListenershould be used instead of inline HTML on* attribute handlers. Another other note: use button instead of link.