This tutorial demonstrates two different ways to create and display an HTML table using JavaScript:
const cars = ["Toyota", "Honda", "BMW", "Ford", "Chevrolet", "Tesla"];
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;
}
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);
}
Now that you have learned both methods, complete the following exercise:
includes() to check if the car exists.forEach() and assign it to innerHTML.forEach().