Dynamically Add Elements with JQuery

by Austin Anderson

HTML

<table id="IAmTheParentYouBindToOnLoad">
  <thead>
    <tr>
      <th>
        Header 1
      </th>
      <th>
        Header 2
      </th>
      <th>
        Header 3
      </th>
    </tr>
    <th>
    </th>
  </thead>
  <tbody id="AddRowsToMe">
      <tr>
        <td>
          Content 1
        </td>
        <td>
          Content 2
        </td>
        <td>
          Content 3
        </td>
        <td>
          <button class="clickable">
          Edit
          </button>
        </td>
      </tr>
  </tbody>
  <tbody>
    <tr>
      <td colspan="4"><button id="myBtn">Add New Row</button></td>
    </tr>
  </tbody>
</table>

JavaScript

$('#myBtn').click(function() {
  var div = $('<tr> <td> Content 1 </td> <td> Content 2 </td> <td> Content 3 </td> <td> <button class="clickable"> Edit </button> </td> </tr>');
  div.appendTo('#AddRowsToMe');
});


$('#IAmTheParentYouBindToOnLoad').on('click', '.clickable', function() {
  alert('injected element clicked');
});