DOM的元素集合和节点列表
HTMLCollection对象
我们通过DOM查找HTML元素的时候,常常会用到getElementsByTagName()和getElementsByClassName(),相比getElementById(),前两个方法返回的是HTMLCollection对象。HTMLCollection 对象类似包含 HTML 元素的一个数组,可以通过数组下标访问元素,但不能使用数组对象的方法。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<p class="content">第一个段落</p>
<p class="content">第二个段落</p>
</div>
<script>
var collection = document.getElementsByTagName( p );
console.log(collection);//HTMLCollection(2)
console.log(collection[0]);//<p id="content1">第一个段落</p>
</script>
</body>
</html>
使用getElementsByClassName(),HTMLCollection 对象的 length 属性定义了集合中元素的数量。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<p class="content">第一个段落</p>
<p class="content">第二个段落</p>
<p class="content">第三个段落</p>
</div>
<script>
var collection = document.getElementsByClassName( content );
console.log(collection);//HTMLCollection(3)
console.log(collection.length);//3
</script>
</body>
</html>
NodeList对象
NodeList 对象是一个从文档中获取的节点列表 (集合) ,大部分浏览器的 querySelectorAll() 返回 NodeList 对象。和HTMLCollection对象一样,NodeList中的元素也可以通过索引来访问。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<p class="content">第一个段落</p>
<p class="content">第二个段落</p>
</div>
<script>
var list = document.querySelectorAll( p );
console.log(list);//NodeList(2)
console.log(list[0]);//<p class="content">第一个段落</p>
console.log(list.length);//2
</script>
</body>
</html>
HTMLCollection和NodeList的区别
HTMLCollection和NodeList有许多的共同点,它们都是类数组,可以通过下标索引来查找元素,但是不能使用数组的方法。区别是HTMLCollection元素可以通过name,id来获取,NodeList不能;NodeList 对象有包含属性节点和文本节点,HTMLCollection则没有属性节点和文本节点。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...


