I want to make a table with vanilla js. But I got a different result depending on where I declare the var.
var body = document.body;
var table = document.createElement('table');
var tr = document.createElement('tr');
var td = document.createElement('td');
body.appendChild(table);
for (var i = 0; i < 3; i +=1) {
table.appendChild(tr);
for (var j = 0; j < 3; j+=1) {
tr.appendChild(td);
td.textContent = 'td';
}
}
I wanted to make 3*3 table. But it made 1*1 table.
var body = document.body;
var table = document.createElement('table');
body.appendChild(table);
for (var i = 0; i < 3; i +=1) {
var tr = document.createElement('tr');
table.appendChild(tr);
for (var j = 0; j < 3; j+=1) {
var td = document.createElement('td');
td.textContent = 'td';
tr.appendChild(td);
}
}
And it was successfully worked. What is difference?
See the docs on appendChild
:
The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position.
In your first code, you create one tr
and one td
, and then in the loops, on each iteration, you remove the tr
and td
from their previous locations before appending them again.
In contrast, in your second code, you're calling createElement
on every iteration, so the new elements that the td
and tr
variables hold do not exist in the document before being appended, so nothing gets removed, and the 3x3 grid gets produced as a result.
It doesn't really have anything to do with scope - it has to do with the fact that you're creating new elements with createElement
instead of re-using the same element you appended in a prior iteration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With