Bybnovskiy Bybnovskiy - 1 month ago 12
HTML Question

table generator by buttons

I have a table with only one td, and I have two buttons one creates tr another td.
The problem is that when I create tr, next td doesn't push in the last created tr.



var table = document.createElement('table');
document.body.appendChild(table)

var tr = document.createElement('tr');
table.appendChild(tr);

var td = document.createElement('td');
tr.appendChild(td);

var createTd = document.createElement('button');
createTd.innerHTML = 'Create td';
document.body.appendChild(createTd);

var createTr = document.createElement('button');
createTr.innerHTML = 'Create tr';
document.body.appendChild(createTr);

createTd.addEventListener('click', function() {
var td = document.createElement('td');
tr.appendChild(td);
})

createTr.addEventListener('click', function() {
var tr = document.createElement('tr');
table.appendChild(tr);
})

td,
tr {
border: 1px solid black;
padding: 10px;
}





You can try demo here : Demo

O_Z O_Z
Answer

The problem is that your created tr is local and you add to the global tr.Just remove the var from the inner tr like this:

createTr.addEventListener('click',function() {
   tr = document.createElement('tr');
  table.appendChild(tr);
})

Here is a working demo

Comments