stephenk Posted February 17, 2008 Share Posted February 17, 2008 I have the following very basic code, however it keeps alerting "0" as the table row count, despite the fact I have a properly formed table in the body. function count() { var myTR = document.getElementsByTagName('tr'); alert(myTR.length); } count(); Full code as follows: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script language="javascript"> function count() { var myTR = document.getElementsByTagName('tr'); alert(myTR.length); } count(); </script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Untitled Document</title> </head> <body> <table width="200" border="1"> <tr> <td>f</td> <td>f</td> <td>f</td> <td>f</td> <td>f</td> </tr> <tr> <td>ef</td> <td>ef</td> <td>ewf</td> <td>ewf</td> <td>ff</td> </tr> <tr> <td>e</td> <td>e</td> <td>e</td> <td>te</td> <td>tew</td> </tr> </table> </body> </html> Any help greatly appreciated, Stephen Quote Link to comment Share on other sites More sharing options...
emehrkay Posted February 17, 2008 Share Posted February 17, 2008 Well, it is becuase the javascript is run before the table is actually loaded into the document do onload = function(){ //add the functions that you want to run on page load here }; or you can simply put the js at the bottom of the page to ensure it fires after loading, but window.onload or onload does just fine Quote Link to comment Share on other sites More sharing options...
bronzemonkey Posted February 17, 2008 Share Posted February 17, 2008 If you're going to have several functions that you need to execute once the document has loaded, you can use this function to do the job: function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { if (oldonload) { oldonload(); } func(); } } } addLoadEvent(count); addLoadEvent(someotherfunction); Quote Link to comment Share on other sites More sharing options...
stephenk Posted February 17, 2008 Author Share Posted February 17, 2008 Excellent, thanks very much, now working! Stephen Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.