Use a <table>
element. <table>
elements have a method called insertRow
which adds a new row to the table, and the row elements <tr>
have a method called insertCell
which adds a new cell to the row element. We'll use both of those to add the data to the table instead of accumulating an html string, like so:
var products = ["Echo Dot", "Echo Plus", "Echo Auto", "Echo Show", "Echo Link"];
var prices = [49.99, 69.99, 129.99, 229.99, 1099.99];
var discountPercent = 20;
var table = document.getElementById("the-table");
for (var i = 0; i < products.length; i++) {
var row = table.insertRow();
row.insertCell().textContent = products[i];
row.insertCell().textContent = prices[i];
row.insertCell().textContent = ((100 - discountPercent) * prices[i] / 100).toFixed(2);
}
table {
border-collapse: collapse;
}
table td, table th {
border: 1px solid black;
padding: 5px 10px;
}
<table id="the-table">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Price After 20% Discount</th>
</tr>
</thead>
</table>
I used textContent
to set the text of the newly added cell instead of innerHTML
that can some problems.