AL-zami AL-zami - 1 month ago 15
Javascript Question

Save the rows from a table's tbody in an array and use them later

It is a part of one of my projects and for this forum I made a simple and short version of it. Here, I had a table first. I saved the rows from it's tbody in an array called

arr[]
. Then I deleted the tbody and created another one. Then I going to append the
tr
enter code here elements saved in
arr[]
to the newly created tbody.

tbody.appendChild(arr[i]);


But it isn't working as the way I want. No tr elements is appended to newly created tbody. How can I make this happen?



var table=document.createElement('table');
var arr=[];
table.setAttribute('style','border:1px solid black;border-collapse:collapse;');
var thead=document.createElement('thead');
thead.setAttribute('style','border:1px solid black;border-collapse:collapse;');
for(i=0;i<1;i++){
var row=thead.insertRow(i);
for(j=0;j<2;j++){
var cell=row.insertCell(j);
cell.setAttribute('style','border:1px solid black;text-align:center;');
cell.innerHTML='tbheadCell'+j;
}

}
table.appendChild(thead);
var tbody=document.createElement('tbody');
tbody.setAttribute('style','border:1px solid black;');
for(i=0;i<2;i++){
var row=tbody.insertRow(i);
for(j=0;j<2;j++){
var cell=row.insertCell(j);
cell.setAttribute('style','border:1px solid black;text-align:center;');
cell.innerHTML='tbodyCell'+j;
}
arr.push(row);
}
table.appendChild(tbody);
document.body.appendChild(table);
table.removeChild(tbody);
var newtbody=document.createElement('tbody');
tbody.setAttribute('style','border:1px solid black;');


console.log(arr);
for(i=0;i<arr.length;i++){
tbody.appendChild(arr[i]);
}
table.appendChild(newtbody);




Answer

in the last loop you are appneding arr to tbody and append newtbody. you should write:

for(i=0;i<arr.length;i++){     
     newtbody.appendChild(arr[i]);
}