Search code examples
javascripthtmlhtml-table

How to insert a row as the second-last row?


There are a lot of similar questions but every single one I could find is using jQuery which I want to mitigate. The content of the inserted row will be created dynamically. My broken approach:

function addRow() {
  let newRow = '<tr><td>Boo</td><td>✔</td><td></td><td>✔</td></tr>';
  document.getElementById('new').insertBefore(newRow);
}
body {
    padding: 50px;
    font-family: sans-serif;
}

table, th, td {
    border: 1px solid #000;
    border-collapse: collapse;
}

th, td {
    padding: 15px;
}

th {
    text-transform: capitalize;
}

#new {
    text-align: center;
    font-weight: bold;
}

#new:hover {
    cursor: pointer;
    background-color: grey;
    color: #fff;
}
<table>
  <tbody>
    <tr>
      <th>title</th>
      <th>multiple</th>
      <th>required</th>
      <th>special</th>
    </tr>
    <tr>
      <td>Bar</td>
      <td>✔</td>
      <td>✔</td>
      <td>✔</td>
    </tr>
    <tr>
      <td>Foo</td>
      <td>✔</td>
      <td></td>
      <td>✔</td>
    </tr>
    <tr>
      <td id="new" colspan="6" onClick="addRow">ADD NEW SETTING</td>
    </tr>
  </tbody>
</table>

Please feel free to optimize the code however you want if you think it should be done differently.


Solution

  • As @Teemu suggested it is better practice to use the HTMLTable Interface instead of using using strings of HTML:

    function addRow() {
      const tbody = document.getElementById('dictionary');
      const row = tbody.insertRow(tbody.rows.length - 1);
      ['Boo', '', '✔', '✔'].forEach(
        cell => row.insertCell().textContent = cell
      );
    }
    body {padding: 50px; font-family: sans-serif;}
    table, th, td {border: 1px solid #000; border-collapse: collapse;}
    th, td {padding: 15px;}
    th {text-transform: capitalize;}
    #new {text-align: center; font-weight: bold;}
    #new:hover {cursor: pointer; background-color: grey; color: #fff;}
    <table>
      <tbody id="dictionary">
        <tr>
          <th>title</th><th>multiple</th><th>required</th><th>special</th>
        </tr>
        <tr>
          <td>Bar</td><td>✔</td><td>✔</td><td>✔</td>
        </tr>
        <tr>
          <td>Foo</td><td>✔</td><td></td><td>✔</td>
        </tr>
        <tr>
          <td id="new" colspan="6" onClick="addRow()">ADD NEW SETTING</td>
        </tr>
      </tbody>
    </table>