I am trying to create a table where each cell consists of a letter and a number. see an image of the target table:
Here is the HTML code that I am using. It's a simple button that when clicked, should call the populateTable()
function and then display the table on the page.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Document</title>
<style>
table { border-collapse: collapse; margin: 1em 0; }
td { border: 1px solid black; padding: 0.3em; }
</style>
</head>
<body>
<h2>Table</h2>
<table id="the-table"></table>
<button type="button" onclick="populateTable();">Populate table</button>
<script src="table.js"></script>
</body>
</html>
But the main issue here is my JS code.
function populateTable(){
letters = ["a", "b", "c", "d", "e"]
numbers = ["1", "2", "3", "4", "5"]
for(let i = 0; i < numbers.length; i++){
document.getElementById("the-table").innerHTML += "<tr>"
for(let j = 0; j < letters.length; j++){
document.getElementById("the-table").innerHTML += "<td>" + letters[j] + numbers[i] + "</td>"
}
document.getElementById("the-table").innerHTML += "</tr>"
}
}
How can I create a new <tr> after inner loop exits?
The outcome of this current code looks like this
Please help :'D
I tried moving around the
document.getElementById("the-table").innerHTML += "<tr>"
and
document.getElementById("the-table").innerHTML += "</tr>"
but to no avail. I tried looking for an answer online, but I found nothing that is useful to my case. things like appendChild were not really what i am looking for exactly. I just want to know why these lines mentioned above ("<tr>") won't work and what's the easiest way to fix this?