Hello I have some problem with my code .I have no clue how to table.appendchild(row)
. I’ve try to do it with append or appendchild but is not working.
My Code:
var body = document.getElementsByTagName('body')[0]; var table = document.createElement('table'); body.appendChild(table); var createrow = function(c1,c2){ var row = document.createElement('tr'); row.appendChild(c1); row.setAttribute('class', 'row') row.appendChild(c2); return row; } var createcell = function(value){ var cell = document.createElement('td'); cell.setAttribute('class', 'cell'); cell.innerText=value; table.appendChild(cell); return cell; } body.appendChild(createrow(createcell('Ion'),createcell('24'))) body.appendChild(createrow(createcell('Gigle'),createcell('26')))
Answer
target.appendChild(another)
means “take this element “another” and place it as a child in the element “target”.
You have made some mistakes in your code. First one is at your createcell
function:
var createcell = function(value){ var cell = document.createElement('td'); cell.setAttribute('class', 'cell'); cell.innerText=value; // table.appendChild(cell); -- uncommented return cell; }
The purpose of this function is to create a “cell” for your table. You are doing that, but you are also doing table.appendChild(cell);
which means that you are placing that cell in the table. That is not correct. I have uncommented it.
Yours createrow
function seems correct.
Finally, you are doing
body.appendChild(createrow(createcell('Ion'),createcell('24')))
which means “take the result of the createrow
function (which is your <tr>
element) and put it in the element “body””. Your body
is the <body>
element. Not something you wanted to give your row to. You want to place the row in your table. So you need to correct that into
table.appendChild(createrow(createcell('Ion'),createcell('24')))
which means “create a row, and place it as child in the element “table””. Yours table
is then the <table>
element. Now the row is placed in the correct location.