I am trying to create a simple math table of 2 printed out in a
tag, below is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Table of 2</h1>
<p id="table-goes-here">Goes here</p>
<script src="script.js"></script>
</body>
</html>
and below is the JS I wrote:
let userNumber = 2;
let tableRow = document.getElementById("table-goes-here");
for(counter = 1; counter <= 12; counter++) {
tableRow.innerHTML = counter + " x " + userNumber + " = " + counter * userNumber + "<br>";
};
my desired output is:
**Table of 2**
1 x 2 = 2
2 x 2 = 4
3 x 2 = 6
4 x 2 = 8
5 x 2 = 10
6 x 2 = 12
7 x 2 = 14
8 x 2 = 16
9 x 2 = 18
10 x 2 = 20
11 x 2 = 22
12 x 2 = 24
In above output the heading would be and the rest all of the table rows will be in a single
tag, but the output that I am getting is:
**Table of 2**
12 x 2 = 24
I am now thinking that my JS code is just repeating itself within the same line and that’s why it’s displaying just the last line of code, I have google a lot on this and also tried n and r solutions but nothing seems to be working I would really appreciate any help 🙂
with that said, I was able to get the desired output with:
let userNumber = 2;
let tableRow = document.getElementById("table-goes-here");
for(counter = 1; counter <= 12; counter++) {
document.write(counter + " x " + userNumber + " = " + counter * userNumber + "<br>");
};
but obviously this way I wasn’t able to place the dynamically generated content into the
tags.
Shahzad S. is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.