Definition and Usage
HTMLCollection
is a collection of elements selected from an HTML document, arranged in the order they appear in the DOM.
This collection is frequently used when working with the DOM and is an iterable, array-like object that lets you treat elements like array items.
Note:
There are two main DOM collections when working with the HTML DOM: HTMLCollection
and NodeList
.
HTMLCollection
is a collection of elements only, whereas NodeList
, depending on how it's created, can include various nodes, such as elements
, text
, and comments
. For more details, see JavaScript HTMLCollection and NodeList Comparison.
Methods That Return HTMLCollection
Objects
getElementsByTagName()
getElementsByClassName()
Note:
There are other methods that also return HTMLCollection
objects; however, these two are the most commonly used and representative methods.
Features
HTMLCollection
is an array-like object and an iterable, which means it can be traversed using thefor...of
loop.- The
length
property returns the number of elements in theHTMLCollection
, just like in an array-like object. HTMLCollection
is a live object that reflects changes in the DOM in real time.
Basic Example
Let's explore how to use HTMLCollection
objects and understand their features through the methods getElementsByTagName()
and getElementsByClassName()
, which return HTMLCollection
objects.
getElementsByTagName()
getElementsByTagName()
returns an HTMLCollection
of all elements that match the specified HTML tag name.
Syntax
// Across the entire HTML document
document.getElementsByTagName(name)
// Within a specific element
element.getElementsByTagName(name)
Example Usage
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTMLCollection</title>
</head>
<body>
<ul>
<li>Pizza</li>
<li>Burger</li>
<li>Pasta</li>
</ul>
<script src="tag-name.js"></script>
</body>
</html>
const liElements = document.getElementsByTagName("li"); // Select all <li> elements
console.log(liElements); // HTMLCollection(3) [li, li, li]
/* Method 1 - Using for...of loop */
for (const liElement of liElements) {
console.log(liElement.textContent);
}
// Output: "Pizza" "Burger" "Pasta"
/* Method 2 - Using traditional for loop */
for (let i = 0; i < liElements.length; i++) { // length property available
console.log(liElements[i].textContent);
}
// Output: "Pizza" "Burger" "Pasta"
/* Method 3 - Convert to an array and use the array's forEach() method */
// Convert to array using spread syntax
const arr = [...liElements];
arr.forEach(li => {
console.log(li.textContent);
});
// Output: "Pizza" "Burger" "Pasta"
// Convert to array using Array.from()
const liElementsArray = Array.from(liElements);
liElementsArray.forEach(li => {
console.log(li.textContent);
});
// Output: "Pizza" "Burger" "Pasta"
Code Explanation
The for...of
loop iterates over iterable objects.
The HTMLCollection
returned by getElementsByTagName()
is both array-like and iterable.
Code Explanation
The traditional for
loop accesses elements using numeric indexes and the length
property, both available on the HTMLCollection
.
Code Explanation
The forEach()
method iterates over an array and executes a callback function on each element. In the code example, this method is used after converting the HTMLCollection
into an array, demonstrating how to access the collection elements using array methods.
Code Explanation
The spread syntax, which consists of three dots ...
, is used by placing it before an iterable object (such as an array, string, or DOM collection) to expand its items individually. This syntax allows an array-like object to be easily converted into a true array.
Code Explanation
Array.from()
is a static method that creates a new array from iterable or array-like objects.
getElementsByClassName()
getElementsByClassName()
selects all elements that match the specified HTML class name and returns them as an HTMLCollection
object.
Syntax
Across the entire HTML document
document.getElementsByClassName(names)
// Within a specific element
element.getElementsByClassName(names)
Example Usage
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTMLCollection</title>
</head>
<body>
<ul>
<li class="menu-item">Pizza</li>
<li class="menu-item">Burger</li>
<li class="menu-item">Pasta</li>
</ul>
<script src="class-name.js"></script>
</body>
</html>
Code Explanation
The HTML class
attribute assigns one or more class names to an element.
const liElements = document.getElementsByClassName("menu-item");
console.log(liElements); // HTMLCollection(3) [li.menu-item, li.menu-item, li.menu-item]
/* Method 1 - Using for...of loop */
for (const liElement of liElements) {
console.log(liElement.textContent);
}
// Output: "Pizza" "Burger" "Pasta"
/* Method 2 - Using traditional for loop */
for (let i = 0; i < liElements.length; i++) {
console.log(liElements[i].textContent);
}
// Output: "Pizza" "Burger" "Pasta"
/* Method 3 - Converting to an array and using the array’s forEach() method */
// Convert to array using spread syntax
const arr = [...liElements];
arr.forEach(li => {
console.log(li.textContent);
});
// Output: "Pizza" "Burger" "Pasta"
// Convert to array using Array.from()
const liElementsArray = Array.from(liElements);
liElementsArray.forEach(li => {
console.log(li.textContent);
});
// Output: "Pizza" "Burger" "Pasta"
Code Explanation
The for...of
loop iterates over iterable objects. The HTMLCollection
returned by getElementsByClassName()
is both array-like and iterable.
Code Explanation
The traditional for
loop accesses elements using numeric indexes and the length
property, both available on the HTMLCollection
.
Code Explanation
The forEach()
method iterates over an array and executes a callback function on each element. In the code example, this method is used after converting the HTMLCollection
into an array, demonstrating how to access the collection elements using array methods.
Code Explanation
The spread syntax, which consists of three dots ...
, is used by placing it before an iterable object (such as an array, string, or DOM collection) to expand its items individually. This syntax allows an array-like object to be easily converted into a true array.
Code Explanation
Array.from()
is a static method that creates a new array from iterable or array-like objects.
Live (or Real-Time) DOM Object
An HTMLCollection
object reflects changes to the DOM in real time (also called "live"). This means that if the DOM is modified after the HTMLCollection
object is created, the object itself will also update automatically. In other words, an HTMLCollection
always represents the current state of the elements on the web page.
The following example demonstrates this behavior: when clicking the "Add New Menu Item" button, a new <li>
element is dynamically added to the <ul>
. The number of <li>
elements returned by document.getElementsByTagName("li")
, i.e., the number of items in the HTMLCollection
, updates live to reflect this change.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>HTMLCollection Live Example</title>
</head>
<body>
<ul id="list">
<li>Seaweed Roll</li>
<li>Ramen</li>
<li>Spicy Rice Cake</li>
</ul>
<p>Number of <code><li></code> elements: <strong id="li-length-val">3</strong></p>
<button type="button" id="addButton">Add New Menu Item</button>
<script src="live.js"></script>
</body>
</html>
// Get the HTMLCollection of <li> elements
const liElements = document.getElementsByTagName("li");
// Add event listener to the button to add a new <li> element
document.getElementById("addButton").addEventListener("click", () => {
const newLi = document.createElement("li");
newLi.textContent = "New Menu Item";
// Append the new <li> element to the <ul> with id "list"
document.getElementById("list").appendChild(newLi);
// Update the displayed count of <li> elements in real-time
const liElementsLength = liElements.length; // Length reflects live updates
document.getElementById("li-length-val").textContent = liElementsLength;
});
Code Explanation
The createElement()
method creates a new HTML element and returns it.
Code Explanation
The getElementById()
method returns the element with the specified id
attribute in the document.
Code Explanation
The appendChild()
method adds a node as the last child of a specified parent node.
- Seaweed Roll
- Ramen
- Spicy Rice Cake
Number of <li> elements: 3
Click the button above to add new items.
You will see the number of <li>
elements update instantly in the HTMLCollection
. This live updating behavior differentiates HTMLCollection
from NodeList
, which does not always reflect real-time DOM changes.
Specifications
Specification | |
---|---|
HTMLCollection
|
DOM Standard #interface-htmlcollection |
Browser compatibility
Object & Property |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
---|---|---|---|---|
HTMLCollection
|
1 | 12 | 1 | 1 |
length
|
1 | 12 | 1 | 1 |