DOM HTMLCollection
An HTMLCollection is a collection of HTML elements.
The HTMLCollection object is similar to an array list that contains HTML elements.
getElementsByTagName() The method returns an HTMLCollection object.
Properties and methods
The following table lists the properties and methods of the HTMLCollection object:
| Attribute / Method | Description |
|---|---|
| item() | Returns the element at the specified index in the HTMLCollection. |
| length | Returns the number of elements in the HTMLCollection. |
| namedItem() | Returns the element with the specified ID or name attribute in the HTMLCollection. |
Example
Returns a collection of all p elements, which is an HTMLCollection object:
Example
var
x
=
document
.
getElementsByTagName
(
"
p
"
)
;
Try it »
Count the number of p elements in the document:
Example
var
x
=
document
.
getElementsByTagName
(
"
P
"
)
;
document
.
write
(
x
.
length
)
;
Try it »
Loop through and output all elements in the HTMLCollection object:
Example
var
x
,
i
,
l
;
x
=
document
.
getElementsByTagName
(
"
"
)
;
l
=
x
.
length
;
for
(
i
=
0
;
i
<
l
;
i
++
)
{
document
.
write
(
x
[
i
]
.
tagName
"
"
)
;
}
Try it »