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>
3
Answers
Use
+=
instead of.insertRow()
:Note:
Id
s 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:
addEventListener
should be used instead of inline HTML on* attribute handlers.Another other note: use button instead of link.
try defining tablerow as a variable, like:
then, inside the add() function, insert a counter for your variable, like so:
You should store the
<tr>
element returned byinsertRow
and manipulate that. It is recommended to use DOM methods instead of inserting raw HTML and in this case, you can callinsertCell
on the row and set itstextContent
.Moreover, ids should be unique in a document, so you should use a class for the rows instead.