Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't know the scope of var

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?

like image 871
kkokko Avatar asked Jan 25 '23 10:01

kkokko


1 Answers

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.

like image 113
CertainPerformance Avatar answered Jan 29 '23 16:01

CertainPerformance