Use JavaScript to change the color of a table by line

Source: Internet
Author: User

By adding an attribute or type selector to the <tr> element, you can use CSS settings to implement a two-color table. However, if the table is very long, it is really troublesome to add elements one by one. In addition, such code is not easy to maintain. Therefore, the better method is to use JS. In fact, in the webpage special effects of the past few days, we have also published such an example, "effect of changing colors of table interlace".

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.

Copy to ClipboardReference: [www.bkjia.com] <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>

Let's take a look at the effect:

<Html> 

Tip: the code can be modified before running!

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.