js获取class对象

!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script>
            window.onload = function() {

                //1、获取表格

//不仅能获得表格对象,可以获得各种类型的对象,例如<span>标签、<p>标签、<div>等

                //通过class属性来获取表格,可以通过getElementsByClassName来获得。采用getElementsByClassName获得的是所有属性为class的表格,为了对其进行区分,需要采用索引tblEle[0]
                var tblEle = document.getElementsByClassName("listtable");
                //2、获取表格中tbody里面的行数
                //采用角标tblEle[0]确定获取的对像。索引从0开始
                var len = tblEle[1].tBodies[0].rows.length;
                //3、对tbody里面的行进行遍历
                for (var i = 0; i < len; i++) {
                    if (i % 2 == 0) {
                        tblEle[1].tBodies[0].rows[i].style.backgroundColor = "yellow";
                    } else {
                        tblEle[1].tBodies[0].rows[i].style.backgroundColor = "green";
                    }
                }
            }
        </script>

    </head>

    <body>
        <table border="1" width="500" height="50" align="center" class="listtable">
            <thead>
                <tr>
                    <th>编号</th>
                    <th>姓名</th>
                    <th>年龄</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>1</td>
                    <td>张三</td>
                    <td>22</td>
                </tr>
                <tr>
                    <td>2</td>
                    <td>李四</td>
                    <td>25</td>
                </tr>
                </tbody>
        </table>
        
       <br />
       <br />
       <table border="1" width="500" height="50" align="center" class="listtable">
            <thead>
                <tr>
                    <th>编号</th>
                    <th>姓名</th>
                    <th>年龄</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>1</td>
                    <td>张三</td>
                    <td>22</td>
                </tr>
                <tr>
                    <td>2</td>
                    <td>李四</td>
                    <td>25</td>
                </tr>
                </tbody>
        </table>
    </body>

</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值