An HTMLCollection is an array-like collection (list) of HTML elements.
The elements in a collection can be accessed by index (starts at 0).
The length Property returns the number of elements in the collection.
An HTMLCollection is almost the same as a NodeList.
See the description below.
The getElementsByTagName() Method
The following properties and methods can be used on an HTMLCollection:
Name | Description |
---|---|
length | Returns the number of elements in an HTMLCollection |
item() | Returns the element at a specified index |
namedItem() | Returns the element with a specified id |
The number of <p> elements in the document are:
const elements = document.getElementsByTagName("p");
let numb = elements.length;
Try it Yourself »
Loop over the elements in an HTMLCollection:
const elements = document.getElementsByTagName("*");
for (let i = 0; i < elements.length; i++) {
.. some code ..
}
Try it Yourself »
An HTMLCollection is not an Array!
An HTMLCollection may look like an array, but it is not.
You can loop through an HTMLCollection and refer to its elements with an index.
But you cannot use Array methods like push(), pop(), or join() on an HTMLCollection.
A NodeList and an HTMLcollection is very much the same thing.
Both are array-like collections (lists) of nodes (elements) extracted from a document. The nodes can be accessed by index numbers. The index starts at 0.
Both have a length property that returns the number of elements in the list (collection).
An HTMLCollection is a collection of document elements.
A NodeList is a collection of document nodes (element nodes, attribute nodes, and text nodes).
HTMLCollection items can be accessed by their name, id, or index number.
NodeList items can only be accessed by their index number.
An HTMLCollection is always a live collection. Example: If you add a <li> element to a list in the DOM, the list in the HTMLCollection will also change.
A NodeList is most often a static collection. Example: If you add a <li> element to a list in the DOM, the list in NodeList will not change.
The getElementsByClassName()
and getElementsByTagName()
methods return a live HTMLCollection.
The querySelectorAll()
method returns a static NodeList.
The childNodes
property returns a live NodeList.
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!