x
1
2
<html>
3
<head>
4
<meta charset="utf-8">
5
<title>蜜蜂教程(mifengjc.com)</title>
6
<style>
7
div {
8
border: 1px solid black;
9
margin: 5px;
10
}
11
</style>
12
</head>
13
<body>
14
15
<div id="myDIV">
16
<p class="child">div 元素中第一个 class="child" 的 p 元素 (索引值为 0).</p>
17
<p class="child">div 元素中第二个 class="child" 的 p 元素 (索引值为 1).</p>
18
<p class="child">div 元素中第三个 class="child" 的 p 元素 (索引值为 2).</p>
19
</div>
20
<p>点击按钮查看 div 元素中类名为 "child" 的元素有几个。</p>
21
<button onclick="myFunction()">点我</button>
22
<p><strong>注意:</strong> Internet Explorer 8 及更早 IE 版本不支持 getElementsByClassName() 方法。</p>
23
<p id="demo"></p>
24
<script>
25
function myFunction() {
26
var x = document.getElementById("myDIV").getElementsByClassName("child");
27
document.getElementById("demo").innerHTML = x.length;
28
}
29
</script>
30
31
</body>
32
</html>