How to create table row in js and append it to a table

How to create table row in js and append it to a table
0

#1

Note: When i run this code i am getting this error
Uncaught TypeError: tbl.appendChild is not a function
** at createTable (script.js:26)**
** at script.js:33**

 
 function createTable() {
 	var tbl = document.getElementsByTagName('table');

    var tblbdy = document.createElement('tbody');

    for (var i = 0; i <= 99; i++){

      var tblrw = document.createElement('tr');

      for (var j = 0; j <= 7; j++){

        var tbltd = document.createElement('td');
        var tbldata = document.createTextNode(j);
        
        tbltd.appendChild(tbldata);
        tblrw.appendChild(tbltd);

      }

      tblbdy.appendChild(tblrw);


    }

      tbl.appendChild(tblbdy);

      alert("done");

 }


 createTable();

#2

That appendChild-function is not a function for tbl-object.
ie: tbl doesn’t have that function.
In such cases make a console.log and then you got that it is a htmlcollection-object.
You can try to access the first element of the collection like this:tbl[0].appendChild.

Info: you created tbl with getElementsByTagName, but you can have more than one table on a page so that collection is required by js.


#3

Hi,
Thanks for your review.

Can i solve this issue by creating tbl with getElementsById ?