<html>
<head>
<style>
div {
border: 1px solid black;
margin: 5px;
}
</style>
</head>
<body>
<div id="myDIV">
<p class="child">div 元素中第一个 class="child" 的 p 元素 (索引值为 0).</p>
<p class="child">div 元素中第二个 class="child" 的 p 元素 (索引值为 1).</p>
<p class="child">div 元素中第三个 class="child" 的 p 元素 (索引值为 2).</p>
</div>
<p>点击按钮查看 div 元素中类名为 "child" 的元素有几个。</p>
<button onclick="myFunction()">点我</button>
<p><strong>注意:</strong> Internet Explorer 8 及更早 IE 版本不支持 getElementsByClassName() 方法。</p>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myDIV").getElementsByClassName("child");
document.getElementById("demo").innerHTML = x.length;
}
</script>
</body>
</html>