In the code below, I am applying a different background color to all even rows by dynamically assigning the class “even” to them using javascript. I am calling the alternamte() function onload of the body tag.
At first, I was using getElementById to get the table object and my code worked fine. However, I am suppose to apply this styling to ALL tables on my page, so I need to use get element by tag name.
Once I made the chane to getElementByTagName, my code stopped working and I have been trying to find out the root of the problem for a while now with no success. I was wondering if someone can help me understand why my code stopped working after I made the change to getElementByTagName?
<script type="text/javascript">
function alternate(){
var table = document.getElementsByTagName("table");
var rows = table.getElementsByTagName("tr");
for(i = 0; i < rows.length; i++){
//change style of even rows
//(odd integer values, since we're counting from zero)
if(i % 2 == 0){
rows[i].className = "even";
}
}
}
</script>
It’s getElementsByTagName(), plural. It returns a HTMLCollection
(if you’re confident that there’s a
<table>on the page.)If you want to do things to all the
<table>elements, you’d have to do something like this: