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?
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?
4 Answers
Reset to default 8You 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"
}
put a class on the rows and put backgrounds in css like you do with the tables
You can try this:
table th {background: color1;}
table tbody {background: color2;}
<table id="t1">
<tr><th>Head1</th><th>Head2</th></tr>
<tbody id="t2">
<tr><td>1</td><td>2</td></tr>
<tr><td>3</td><td>4</td></tr>
</tbody>
</table>
And in the script:
document.getElementById('t2').style.backgroundColor=color3;
EDIT
It's also possible to add a rule to the particular styleSheet
.
CSS:
table th {background: color1;}
table td {background: color2;}
Script:
var sSheet = document.styleSheets[0];
if (sSheet.insertRule) {
sSheet.insertRule('td {background-color: color3}', sSheet.cssRules.length);
} else { // For IE < 9
sSheet.addRule('td', 'background-color: color3', -1);
}
You can also modify an existing rule itself:
var tdRule,
sSheet = document.styleSheets[0];
if (sSheet.cssRules) {
tdRule = sSheet.cssRules[1];
} else { // For IE < 9
tdRule = sSheet.rules[1];
}
tdRule.style.backgroundColor = color3;
I use JQuery.
$('td').css('background','#3232');
th
andtd
already have different colorscolor1
andcolor2
so aren't they already different? – Anjan Biswas Commented Aug 9, 2012 at 18:06