Jeff Jeff - 7 months ago 15
Javascript Question

Setting the style property for table rows using javascript

Assume I have a page like this

<html>
<body>
<table id="t1">
<tr><th>Head1</th><th>Head2</th></tr>
<tr><td>1</td><td>2</td></tr>
<tr><td>3</td><td>4</td></tr>
</table>
</body>
</html>


My CSS

table th { background:color1;}
table td { background:color2;}


How do I change the background color for all rows except header row with a javascript statement. Is looping through each row and column the only method?

I can get
document.getElementById('t1').rows[1]
and
rows[2]
and change background. But is there another efficient way?

Answer

You can loop over the elements and change the background

var els = document.getElementById("t1").getElementsByTagName("td");

for(var i=0;i<els.length;i++){
  els[i].style.background = "green"   
}