Code for implementing two-color table in JS

Source: Internet
Author: User

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>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.