Tutorial: Displaying Data in an HTML Table using JavaScript

This tutorial demonstrates two different ways to create and display an HTML table using JavaScript:

  1. Building the table as a string of HTML code.
  2. Creating the table dynamically using JavaScript DOM objects.

Example Data

const cars = ["Toyota", "Honda", "BMW", "Ford", "Chevrolet", "Tesla"];

Method 1: Creating a Table as an HTML String

In this method, we build the entire HTML table as text and assign it to a web page element using innerHTML.


function showCarsWithHTML() {
  let tableHTML = "<table border='1'><tr><th>Car Name</th></tr>";

  cars.forEach(car => {
    tableHTML += "<tr><td>" + car + "</td></tr>";
  });

  tableHTML += "</table>";
  document.getElementById("carTable1").innerHTML = tableHTML;
}
  

Method 2: Creating a Table Using DOM Objects

In this method, we use JavaScript DOM methods to create table elements. This approach is more flexible when you want to modify the table dynamically.


function showCarsWithDOM() {
  const container = document.getElementById("carTable2");
  container.innerHTML = "";

  const table = document.createElement("table");
  table.border = "1";

  const headerRow = document.createElement("tr");
  const headerCell = document.createElement("th");
  headerCell.textContent = "Car Name";
  headerRow.appendChild(headerCell);
  table.appendChild(headerRow);

  cars.forEach(car => {
    const row = document.createElement("tr");
    const cell = document.createElement("td");
    cell.textContent = car;
    row.appendChild(cell);
    table.appendChild(row);
  });

  container.appendChild(table);
}
  

Exercise: Car Search and Display Application

Now that you have learned both methods, complete the following exercise:

Question 1: Car Search

Question 2: Display All Cars