steady_progress steady_progress - 19 days ago 6
HTML Question

t_body.children[k].appendChild(var) throws an error

Consider the following js-loop:

for (var i=0;i<diff;++i){
for (var j=0; j<old_col_num; ++j){
var t_col = document.createElement("td");
//the following line throws an error:
t_body.children[old_row_num+1+i].appendChild(t_col);
}
}


The error message I get is the following:

Uncaught TypeError: Cannot read property 'appendChild' of undefined(…)


I don't understand why it doesn't work. If I put in a fixed number instead of "old_row_num+1+i" there is no error (but I need the flexibility in my program).

UPDATE:

the whole function looks as follows:

function change_dim_r(diff) {

var old_row_num = t_body.childElementCount;
var old_col_num = t_body.children[0].childElementCount;

for (var i=0; i<diff; ++i){
var new_t_row = document.createElement("tr");
t_body.appendChild(new_t_row);
}

for (var i=0;i<diff;++i){
for (var j=0; j<old_col_num; ++j){
var t_col = document.createElement("td");
t_body.children[old_row_num+1+i].appendChild(t_col);
}
}
}

Answer

I believe your old row number is inaccurate.

var old_row_num = t_body.children.childElementCount;

If you want the number of rows you wouldn't do .children there.

function change_dim_r(diff) {

  var t_body = document.querySelector("tbody");
  var old_row_num = t_body.childElementCount;
  var old_col_num = t_body.children[0].childElementCount;

  for (var i = 0; i < diff; ++i) {
    var new_t_row = document.createElement("tr");
    t_body.appendChild(new_t_row);
  }

  for (var i = 0; i < t_body.childElementCount; ++i) {
    var t_row = t_body.children[i];
    
    for (var j = t_row.childElementCount; j < t_body.childElementCount; ++j) {
      var t_col = document.createElement("td");
      t_row.appendChild(t_col);
    }
  }
}

change_dim_r(10);
<table border="1" cellpadding="2" cellspacing="2">
  <tbody>
    <tr>
      <td></td>
    </tr>
  </tbody>
</table>