THE WORLD'S LARGEST WEB DEVELOPER SITE

DOM HTMLCollection


The HTMLCollection Object

An HTMLCollection object is an array-like list of HTML elements.

Methods like the getElementsByTagName() returns an HTMLCollection.


Properties and Methods

The following properties and methods can be used on a HTMLCollection object:

Property / Method Description
item() Returns the element at the specified index in an HTMLCollection
length Returns the number of elements in an HTMLCollection
namedItem() Returns the element with the specified ID, or name, in an HTMLCollection

Examples

Example

Get an HTMLCollection:

var x = document.getElementsByTagName("P");
// Returns a collection of all the P elements in the document
Try it Yourself »

Example

Write the number of <P> elements in the document:

var x = document.getElementsByTagName("P");
document.write(x.length);
Try it Yourself »

Example

Loop through every element in an HTMLCollection:

x = document.getElementsByTagName("*");
l = x.length;
for (i = 0; i < l; i++) {
  document.write(x[i].tagName + "<br>");
}
Try it Yourself »