Home > Javascript > Dynamically Creating HTML Tables, Rows And Cells

Dynamically Creating HTML Tables, Rows And Cells

July 20th, 2009

Requires only a placeholder table, under which new rows and cells will be added later

<table id="myTable1">
  <tbody>
  </tbody>
</table>

To add a row to this table

  var rowX = $("<tr>"); rowX.appendTo(tableToAddTo);

To add a cell at a specific index in this row

1
2
3
4
5
6
7
8
  function createTableRowCell(rowToAddTo, columnIndex, idToAssign, cellContents, cellClass)  {
  $("<td>")
    .addClass(cellClass)
    .text(cellContents)
    .data("col", columnIndex)
    .attr("id",idToAssign)
    .appendTo(rowToAddTo);
}

Example, here a row is being added to the table “myTable1″ and then a cell is being added to the recently-added row at index 0.

  var tableToAddTo = $("#myTable1");
  var rowX = $("<tr>"); rowX.appendTo(tableToAddTo);
  var cellY = createTableRowCell(rowX, 0, taskId, taskTitle, "someClassTBD");
Categories: Javascript Tags: ,
Comments are closed.