The principle is actually very simple: Use getElementsByTagName to get all the <tr> elements, and then add background colors for the <tr> elements of the odd and even items respectively.
Core code:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function color (){
// Set the header to purple
Var th = document. getElementById ("th ");
Th. style. background = "violet"
// 1. Obtain all <tr> Elements
Var trs = document. getElementsByTagName ("tr ");
Var I;
For (I = 1; I <trs. length; I ++ ){
// 2. Change the background color of the <tr> element.
If (I % 2 = 0 ){
Trs [I]. style. background = "yellow ";
} Else {
Trs [I]. style. background = "olive ";
}
}
}
Window. onload = color;
</Script>
All code:
Copy codeThe Code is as follows:
<Html>
<Head>
<Title> two-color table </title>
<Style type = "text/css">
<! --
Table {
Border: solid 1px black;
Text-align: center;
Border-spacing: 0px;
}
Th, td {
Border: solid 1px black;
Width: 100px;
}
-->
</Style>
<Script type = "text/javascript">
Function color (){
// Set the header to purple
Var th = document. getElementById ("th ");
Th. style. background = "violet"
// 1. Obtain all <tr> Elements
Var trs = document. getElementsByTagName ("tr ");
Var I;
For (I = 1; I <trs. length; I ++ ){
// 2. Change the background color of the <tr> element.
If (I % 2 = 0 ){
Trs [I]. style. background = "yellow ";
} Else {
Trs [I]. style. background = "olive ";
}
}
}
Window. onload = color;
</Script>
</Head>
<Body>
<Center>
<Table>
<Tr id = "th">
<Th> name </th>
<Th> subject </th>
<Th> score </th>
</Tr>
<Tr>
<Td> JOHN </td>
<Td> language </td>
<Td> 90 </td>
</Tr>
<Tr>
<Td> JOHN </td>
<Td> mathematics </td>
<Td> 87 </td>
</Tr>
<Tr>
<Td> Li Si </td>
<Td> mathematics </td>
<Td> 68 </td>
</Tr>
<Tr>
<Td> Wang Wu </td>
<Td> English </td>
<Td> 76 </td>
</Tr>
</Table>
</Center>
</Body>
</Html>