Suppose we have such an empty HTML table:
<table id="table"></table>
Let's populate this table with cells and make these cells
contain numbers from 1
to 9
. Here is an
example of what we should get:
<table id="table">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>
Let's get started with the implementation.
First, let's just make a table of 3
by 3
size, filled with letters 'x'
:
let table = document.querySelector('#table');
for (let i = 0; i < 3; i++) {
let tr = document.createElement('tr');
for (let i = 0; i < 3; i++) {
let td = document.createElement('td');
td.textContent = 'x';
tr.appendChild(td);
}
table.appendChild(tr);
}
Let's now make it so that instead of the letters 'x'
,
numbers are written into the cells in ascending order.
To do this, we need to introduce another counter, which will sequentially increase its values in each iteration of the inner loop, like this:
let table = document.querySelector('#table');
let k = 1; // a counter initial value
for (let i = 0; i < 3; i++) {
let tr = document.createElement('tr');
for (let i = 0; i < 3; i++) {
let td = document.createElement('td');
td.textContent = k; // writes the counter to the cell
k++; // increments the counter
tr.appendChild(td);
}
table.appendChild(tr);
}
Display an HTML table of 5
rows by 5
columns so that its cells contain consecutive
numbers from 1
to 25
.
Modify the previous task so that even numbers in
the interval from 2
to 50
are
written in the table cells.