根据:html中document.getElementsByClassName() 方法_徊忆羽菲的博客-优快云博客_document.getelementbyclassname()
- document.getElementsByClassName()方法返回文档中所有指定类名的元素集合,作为NodeList对象
- NodeList 对象代表一个有顺序的节点列表。 NodeList对象,我们可以通过节点列表中的节点索引号来访问列表中的节点(索引号从0开始)
- 提示:你可以使用NodeList对象的length属性来确定指定类名的元素个数,并循环各个元素来获取你需要的那个元素
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>document.getElementsByClassName()的学习1</title>
</head>
<body>
<ul class="dongdongdong">
<li class="child">meitiankaixin</li>
<li class="child">xiaodong</li>
</ul>
<p>点击按钮修改第一个列表项的文本信息 (索引值为 0)。</p>
<button onclick="myFunction()">点我</button>
<p><strong>注意:</strong> Internet Explorer 8 及更早 IE 版本不支持 getElementsByClassName() 方法。</p>
<script>
function myFunction() {
var list = document.getElementsByClassName("dongdongdong")[0];
console.log(document.getElementsByClassName("dongdongdong"),"获取类名");//dongdongdong,集合 HTMLCollection [ul.dongdongdong]
console.log(document.getElementsByClassName("dongdongdong").length,"获取类名的长度");// 1
console.log(document.getElementsByClassName("dongdongdong")[0],"获取类名的第0项"); // dongdongdong 和他的子元素
list.getElementsByClassName("child")[0].innerHTML = "shengrikuaile";
console.log(list.getElementsByClassName("child"),"子元素的类名"); // 是两个child HTMLCollection(2) [li.child, li.child]
console.log(list.getElementsByClassName("child").length,"子元素的类名长度"); // 2
console.log(list.getElementsByClassName("child")[0],"子元素的类名的第一项"); // meitiankaixin,不过被改成了shengrikuaile
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>document.getElementsByClassName()的学习2</title>
<style>
div {
border: 1px solid pink;
margin: 5px;
}
</style>
</head>
<body>
<div id="发财发财">
<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 元素中第二个 class="child" 的 p 元素添加背景颜色。</p>
<button onclick="myFunction()">点我</button>
<p><strong>注意:</strong> Internet Explorer 8 及更早 IE 版本不支持 getElementsByClassName() 方法。</p>
<script>
function myFunction() {
var x = document.getElementById("发财发财");
x.getElementsByClassName("child")[1].style.backgroundColor = "yellow";
}
</script>
</body>
</html>