I have a query building form built in PHP. The results of the query are returned and placed in two different tables one above the other. (table id’s are results, and results2) Each record returned builds two tables to display its data. (Soon to be three)
I’m using the following code to change the class tags of my <tr>‘s to provide alternate row coloring:
<script type="text/javascript">
function alternate(id){
if(document.getElementsByTagName){
var table = document.getElementById(id);
var rows = table.getElementsByTagName("tr");
for(i = 0; i < rows.length; i++){
if(i % 2 == 0){
rows[i].className = "row-one";
}else{
rows[i].className = "row-two";
}
}
}
}
</script>
Then I’m using a body onload like so:
<body onload="alternate('results'); alternate('results2');">
The problem is it only colors the first two instances of these tables, when depending on the amount of records returned there could be hundreds of them.
How can I get this function to apply to every table in the document with a id = results and results2 and soon to be a results3?
If you really want to do this with JavaScript, I would suggest the following code:
First, make your tables have a class of “results” instead of ID “results1”, “results2”, etc (because as my comment on the question says, IDs must be unique, and getElementById will only return one result and apply to only one real element):
Next, use this JavaScript:
Then call
alternate("results");on page load.But, I really suggest doing this in PHP. JavaScript will be very inefficient with large result sets. It will also not show up right away, making the style of the page visibily change after page load.
I would also just add a class to every other row, and then style all rows by default one way and the other class the other way: