实例代码“Ctrl+/”提示“F11/ESC”全屏 返回 格式化 恢复 运行
x
 
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<style>
5
div {
6
    border: 1px solid black;
7
    margin: 5px;
8
}
9
</style>
10
</head>
11
<body>
12
13
<div id="myDIV"> 
14
  <p class="child"> div 元素中 class="child" 的 p </p>
15
  <p class="child"> div 元素中 class="child" 的另外一个 p </p>
16
  <p>在 div 中的 p 元素插入 <span class="child">class="child" 的 span 元素</span></p>
17
</div>
18
19
<p>点击按钮为 id="myDIV" 的 div 元素中所有 class="child" 元素添加背景颜色。 the div element with id="myDIV".</p>
20
21
<button onclick="myFunction()">点我</button>
22
23
<p><strong>注意:</strong> Internet Explorer 8 及更早 IE 版本不支持 getElementsByClassName() 方法。</p>
24
25
<script>
26
function myFunction() {
27
    var x = document.getElementById("myDIV");
28
    var y = x.getElementsByClassName("child");
29
    var i;
30
    for (i = 0; i < y.length; i++) {
31
        y[i].style.backgroundColor = "red";
32
    }
33
}
34
</script>
35
36
</body>
37
</html>
38