获取html元素集合对象
The getElementsByTagName()
method returns an HTMLCollection object.
An HTMLCollection object is an array-like list (collection) of HTML elements.
The following code selects all <p>
elements in a document:
var x=document.getElementsByTagName("p");
访问html元素集合的某个元素
The elements in the collection can be accessed by an index number.
获取HTML元素集合长度
The length
property defines the number of elements in an HTMLCollection:
var x=document.getElementsByTagName("p");
alert(x.length);
遍历HtmlCollection
当您想要遍历集合中的元素时,length属性很有用:
示例(Change the background color of all <p>
elements:)
<body>
<div id="div1">
<p id="p1">This is a paragrap.</p>
<p id="p2">This is another paragrap.</p>
</div>
<button id="myBtn">change p color to red</button>
</body>
<!--javascript-->
<script>
document.getElementById("myBtn").addEventListener("click",myFunction);
function myFunction(){
var x=document.getElementsByTagName("p");
var i;
for(i=0;i<x.length;i++)
{
x[i].style.color="red";
}
}
</script>
HTMLCollection不是数组!
An HTMLCollection may look like an array, but it is not. You can loop through the list and refer to the elements with a number (just
like an array). However, you cannot use array methods like valueOf(),
pop(), push(), or join() on an HTMLCollection.
获取节点列表对象(NodeList)
NodeList对象是从文档中提取的节点列表(集合)。
A NodeList object is almost the same as an HTMLCollection object.
一些(较旧的)浏览器为诸如getElementsByClassName()之类的方法返回NodeList对象而不是HTMLCollection。
所有浏览器都为属性childNodes返回一个NodeList对象。
大多数浏览器为方法querySelectorAll()返回NodeList对象。
以下代码选择文档中的所有<p>
节点:var myNodeList=document.querySelectorAll("p");
访问节点列表中的某个节点
The elements in the NodeList can be accessed by an index number.
To access the second
node you can write:var node2=myNodeList[1];
获取节点列表长度
The length property defines the number of nodes in a node list:
var myNodeList=document.querySelectorAll("p");
alert(myNodeList.length);
遍历节点列表
当您要遍历节点列表中的节点时,length属性很有用:
<body>
<div id="div1">
<p id="p1">This is a paragrap.</p>
<p id="p2">This is another paragrap.</p>
<p >hello.</p>
</div>
<button id="myBtn">change p color </button>
</body>
<!--javascript-->
<script>
document.getElementById("myBtn").addEventListener("click",myFunction);
function myFunction(){
var myNodeList=document.querySelectorAll("p");
var i;
for(i=0;i<myNodeList.length;i++)
{
myNodeList[i].style.color="pink";
}
}
</script>
HTMLCollection和NodeList之间的区别
- HTMLCollection是HTML元素的集合。
- NodeList是文档节点的集合。
- NodeList节点列表和HTML元素集合几乎是同一件事。
- HTMLCollection对象和NodeList对象都是类似数组的对象列表(集合)。
- 两者都具有length属性,该属性定义列表(集合)中的项目数。
- 两者都提供索引(0、1、2、3、4,…)以像数组一样访问每个项目。
- 可以通过名称,ID或索引号访问HTMLCollection项目。
- 只能通过其索引号访问NodeList项。
- 只有NodeList对象可以包含属性节点和文本节点。
- HTMLCollection和NodeList不是数组!