Issue
I would like to write a JavaScript function that generates the following HTML Table:
| x | x^2 | 1/x |
|---------------|
| 1 | 1 | 1 |
|---|-----|-----|
| 4 | 16 | 0.25|
And here is my code so far. I have to use a FOR LOOP to construct and tags to place the values of x, x^2, and 1/x into the table. It's incomplete because I'm not really sure what to do from this point. Any help would be appreciated!!
<!DOCTYPE html>
<html>
<head>
<style>
table {
border: 1px solid black;
width:50%;
border-collapse:collapse;
align:center;
}
th {
align:center;
font-weight:bold;
border: 1px solid black;
}
</style>
<script>
function square(n)
{
var sqNum = n * n;
return sqNum;
}
function inverse(n)
{
var invNum = 1 / n;
return invNum;
}
function generateTable()
{
var tableMain = document.getElementById("table");
for (var i = 0; i <= 5; i++)
{
var x = i;
var xSquare = square(i);
var xInv = inverse(i)
</script>
</head>
<body>
<table id="table">
<tr bgcolor="gainsboro">
<th>x</th>
<th>X<sup>2</sup></th>
<th><sup>1</sup>/<sub>x</sub></th>
</tr>
</table>
</body>
<html>
Solution
Use insertAdjacentHTML
and a template literal to create a row.
generateTable();
function generateTable(n = 5) {
const square = n => n * n;
const inverse = n => 1 / n;
const tableMain = document.querySelector("table");
for (let i = 1; i <= n; i++) {
tableMain.insertAdjacentHTML(
`beforeend`,
`<tr><td>${i}</td><td>${square(i)}</td><td>${inverse(i).toFixed(2)}</td></tr>`)
}
}
table {
border: 1px solid black;
border-collapse: collapse;
text-align: center;
}
th, td {
text-align: center;
font-weight: bold;
border: 1px solid black;
padding: 1px 6px;
}
td {
font-weight: normal;
}
<table id="table">
<tr bgcolor="gainsboro">
<th>x</th>
<th>X<sup>2</sup></th>
<th><sup>1</sup>/<sub>x</sub></th>
</tr>
</table>
Answered By - KooiInc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.