Search code examples
javascripthtmlcsshtml-table

Add ID to table row with JavaScript?


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>


Solution

  • Use += instead of .insertRow():

    const btnAdd = document.querySelector("#add");
    btnAdd.addEventListener("click", add)
    let idCounter = 0;
    function add() {
      document.getElementById("tbody").innerHTML += `
          <tr id="tablerow${idCounter++}">
            <td>Table row ${idCounter}</td>
          </tr>
        `;
    }
    <table>
      <thead>
        <tr>
          <th>Table Head</th>
          <th></th>
        </tr>
      </thead>
      <tbody id="tbody">
      </tbody>
    </table>
    <button id="add">Click to add a table row</button>

    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 use class='tablerow'
    Another note: addEventListener should be used instead of inline HTML on* attribute handlers. Another other note: use button instead of link.