实例代码“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 元素 (索引值为 0).</p>
15
  <p class="child">div 元素中第二个 class="child" 的 p 元素 (索引值为 1).</p>
16
  <p class="child">div 元素中第三个 class="child" 的 p 元素 (索引值为 2).</p>
17
</div>
18
19
<p>点击按钮为 div 元素中第二个 class="child" 的 p 元素添加背景颜色。</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
    x.getElementsByClassName("child")[1].style.backgroundColor = "red";
29
}
30
</script>
31
32
</body>
33
</html>
34