English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JS DOM HTMLCollection Object

HTMLCollection object

The HTMLCollection object represents a general collection of elements (in document order) (similar to an array object, similar to a parameter) and provides methods and properties for selection from the list.

The HTMLCollection in HTML DOM is live; it updates automatically when the underlying document changes.

Methods like getElementsByTagName() return HTMLCollection.

HTMLCollection Properties and Methods

The following table lists the properties and methods of the HTMLCollection object:

Property/MethodDescription
item()Return the element at the specified index in the HTMLCollection
lengthReturn the number of elements in the HTMLCollection
namedItem()Return the element with the specified ID or name in the HTMLCollection

Example

This example returns an HTMLCollection:

// Return the set of elements in the collection document of <p>
var x = document.getElementsByTagName("p");
Test and see‹/›

Change the HTML content of the first <p> element in this document:

var x = document.getElementsByTagName("p");
x.item(0).innerHTML = "HELLO WORLD";
Test and see‹/›

Find out how many <p> elements are in the document:

var len = document.getElementsByTagName("p").length;
Test and see‹/›

Get the content of the <p> element with ID "demo":

var x = document.getElementsByTagName("p").namedItem("demo");
document.getElementById("output").innerHTML = x.innerHTML;
Test and see‹/›

You can also use a shorthand method, which will produce the same result:

var x = document.getElementsByTagName("p")["demo"];
document.getElementById("output").innerHTML = x.innerHTML;
Test and see‹/›