How to make a javaScript table

Learn how to create a JavaScript table with an example code snippet. Understand how to customize the table to fit your needs.

Creating a JavaScript Table

Creating a table using JavaScript can be done by using the document.createElement() to create a table and then using the appendChild() method to add the table to the HTML document. The following example shows how to create a simple table with three columns and three rows.


// Create a Table element
let table = document.createElement("table");

// Create table body
let tbody = document.createElement("tbody");

// Cells
for (let i = 0; i < 3; i++) {
  // Create a row
  let row = document.createElement("tr");

  for (let j = 0; j < 3; j++) {
    // Create a cell
    let cell = document.createElement("td");

    // Create the text node for the cell
    let cellText = document.createTextNode("cell is row "+i+", column "+j);

    // Add the text to the cell
    cell.appendChild(cellText);

    // Add the cell to the row
    row.appendChild(cell);
  }

  // Add the row to the table body
  tbody.appendChild(row);
}

// Add the body to the table
table.appendChild(tbody);

// Append table to the HTML document
document.body.appendChild(table);

The code above will create a table with three columns and three rows and add it to the HTML document. The table will look like this:

cell is row 0, column 0 cell is row 0, column 1 cell is row 0, column 2
cell is row 1, column 0 cell is row 1, column 1 cell is row 1, column 2
cell is row 2, column 0 cell is row 2, column 1 cell is row 2, column 2

This example shows how to create a simple table using JavaScript. To make the table more complex, such as adding classes or styles to the table, you can use the setAttribute() method to set the attributes on the table and the cells.

Answers (0)