Jump to content

Counting table rows


stephenk

Recommended Posts

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.