首页 > 代码库 > Javascript通过className选择元素

Javascript通过className选择元素

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script type="text/javascript">
 
        window.onload = function () {
            var oUl = document.getElementById("ul1");
            var aLi = oUl.getElementsByTagName("li");
 
            for (var i = 0; i < aLi.length; i++) {
                if (aLi[i].className == "box") {
                    aLi[i].style.background = "red";
                }
            }
        }
 
        //封装了一个方法,通过class选取元素
        function getByClass(oParent, sClss) {
            var aResult = [];
            var aEle = oParent.getElementsByTagName("*");
            for (var i = 0; i < aEle.length; i++) {
                if (aEle[i].className == "sClss") {
                    aEle[i].style.background = "red";
                    aResult.push(aEle[i]);
                }
            }
        }
    </script>
</head>
<body>
    <ul id="ul1">
        <li class="box"></li>
        <li></li>
        <li class="box"></li>
        <li></li>
        <li class="box"></li>
        <li></li>
        <li class="box"></li>
        <li class="box"></li>
    </ul>
    <!--
        元素属性的操作
        第一种:oDiv.style.display="none";
        第二种:oDiv.style["display"]="none";
        第三种:Dom方式
 
        Dom方式操作元素的属性
        获取:getAttribute(名称);//99%一般用不着他
        设置:setAttribute(名称,值);
        删除:removeAttribute(名称);
 
 
        用className选择元素
        -->
</body>
</html>