javascript - Cannot read property of 'appendchild' of null in a For-Loop -
i have small database have retrieved data , stored in html table.
this table contains 3 columns , 3 rows.
what want via javascript create div each row, within create div each cell in row of table (to allow me style in css).
i have created number of loops go through , attempt this, problem second loop have created, goes through once , receive error of "cannot read property 'appendchild' of null". not sure why doing this. appreciated.
var gettable = document.getelementbyid('projectstable'); var rowlength = gettable.rows.length; (i =0; i< rowlength; i++) { var divname = 'projects' + i; block = document.createelement('div'); block.id = divname; document.getelementbyid('javascript').appendchild(block); var getcells = gettable.rows.item(i).cells; var celllength = getcells.length; (var j = 0; j < celllength; j++) { var divname2 = 'projects' + j; var projectinfo = 'info' + j; info = document.createelement('div'); info.id = projectinfo; document.getelementbyid(divname2).appendchild(info); var cellval = getcells.item(j).innerhtml; var getdiv = document.getelementbyid(projectinfo); getdiv.innerhtml = cellval; } }
the first loop creates div whole row , attaches div in page exists, error on 2nd loop.
you using many unnecessary variables , definitions. example divname2 should same divname , redundant. hope example helps out.
<!doctype html> <html> <head> <script> function loadtable(){ var tt = document.getelementbyid('projectstable'); //source table var tj = document.getelementbyid('javascript'); //new clone container if (tt && tj){ for(var i=0, j=tt.rows.length;i<j;i++){ var tp = document.createelement('div'); //our project div(:=tr) tp.id = 'projects' + i.tostring(); for(k=0, l=tt.rows.item(i).cells.length;k<l;k++){ var ti = document.createelement('div'); //our info div(:=td) ti.id = 'info' + k.tostring(); ti.innerhtml = (i+1)*k; tp.appendchild(ti); //we still have correct project above, use it. }; tj.appendchild(tp); //adding project dom }; }; }; </script> </head> <body onload = 'loadtable();'> <table id = 'projectstable'> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>4</td><td>5</td><td>6</td></tr> </table> <div id = 'javascript'></div> </body> </html>
Comments
Post a Comment