代码编辑器:
x
1
<style>
2
div {
3
border: 1px solid black;
4
margin: 5px;
5
}
6
</style>
7
<div id="myDIV">
8
<p class="child">div 元素中第一个 class="child" 的 p 元素 (索引值为 0).</p>
9
<p class="child">div 元素中第二个 class="child" 的 p 元素 (索引值为 1).</p>
10
<p class="child">div 元素中第三个 class="child" 的 p 元素 (索引值为 2).</p>
11
</div>
12
<p>点击按钮为 div 元素中第二个 class="child" 的 p 元素添加背景颜色</p>
13
<button onclick="myFunction()">点我</button>
14
<p><strong>注意:</strong> Internet Explorer 8 及更早 IE 版本不支持 getElementsByClassName() 方法</p>
15
<script>
16
function myFunction() {
17
var x = document.getElementById("myDIV");
18
x.getElementsByClassName("child")[1].style.backgroundColor = "red";