Yara
Yara

Reputation: 1

Counting elements with Javascript

I am kind of a newbie, so I am not sure where to look for my mistake. I am want to count all rows of a certain table, but I need to have the number above/inside the table itself. However, I only get the number of rows above the point where I call the function, but I need the number of rows of the entire table.

(...)
<script type="text/javascript">
function countRows()
{
   rowsCount = document.getElementById("list").rows.length;
   return rowsCount;
}
</script>

<body>

<table id="list">
<tr><td>
There are 
<script type="text/javascript"> document.write(countRows()) </script> 
rows here. // Returns "1"
</td></tr>

<tr><td>(Stuff goes here)</td></tr>
<tr><td>(Stuff goes here)</td></tr> // script would return "3" here.
<tr><td>(Stuff goes here)</td></tr>
<tr><td>(Stuff goes here)</td></tr>
(...)

No jQuery here! I know it is nice, but I can't use it in this case.

Upvotes: 0

Views: 2782

Answers (1)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

Try this:

window.onload = function()
{
    var tbl = document.getElementById("list");
    document.body.innerHTML += tbl.lrows.length;//or tbl.rows[0].cells[0].innerHTML
};

The onload event fires after the page is fully loaded, this includes the full table. You can't count the number of rows until they're all there... makes sense, doesn't it? :P

Oh, and please, since you're learning still, don't learn the wrong things, like document.write: it's flawed in a bad way.
I know it doesn't seem important at this point, but also note that you're creating the most evil of variables with rowsCount: an implied global. Don't, just don't ever do that. Get in the habit of declaring all variables you want to use, as to not clutter the global namespace. (That, and if you don't your script will fail in strict mode).

Upvotes: 4

Related Questions