skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. try defining tablerow as a variable, like:

    let tablerow = 1
    

    then, inside the add() function, insert a counter for your variable, like so:

    let tablerow = 1;
      function add() {
      document.getElementById("tbody").insertRow().innerHTML = `
          <tr id=`${tablerow++}`> <!-- The ID don't work -->
            <td>
                Table row
            </td>
          </tr>
        `;
    }
    
    Login or Signup to reply.
  3. You should store the <tr> element returned by insertRow and manipulate that. It is recommended to use DOM methods instead of inserting raw HTML and in this case, you can call insertCell on the row and set its textContent.

    Moreover, ids should be unique in a document, so you should use a class for the rows instead.

    document.querySelector('#add').addEventListener('click', function() {
      const row = document.getElementById("tbody").insertRow();
      row.className = 'tablerow';
      row.insertCell().textContent = 'Table row';
    });
    #add {
      cursor: pointer;
    }
    .tablerow {
      background: #f00;
    }
    <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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search