Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript HTML DOM Collections (Collection)

JavaScript HTML DOM Collections (Collection)

This chapter introduces the use of DOM collections.


The HTMLCollection Object

The getElementsByTagName() method returns a HTMLCollection object.

The HTMLCollection object is similar to an array containing HTML elements.

The following code gets all of the document's

element:

Example

var

x

=

document

.

getElementsByTagName

(

"

p

"

)

;

Elements in a collection can be accessed by index (starting at 0).

Access the second

element with the following code:

y = x[1];

Try it »


The HTMLCollection Object length Property

The length property of the HTMLCollection object defines the number of elements in the collection.

Example

var

myCollection

=

document

.

getElementsByTagName

(

"

p

"

)

;

document

.

getElementById

(

"

demo

"

)

.

innerHTML

=

myCollection

.

length

;

Try it »

Example Parsing

Obtain the

A collection of elements:

var myCollection = document.getElementsByTagName("p");

Display the number of elements in the collection:

document.getElementById("demo").innerHTML = myCollection.length;

The collection's length property is often used to iterate over the elements in the collection.

Example

Modify all

elements' background color:

var

myCollection

=

document

.

getElementsByTagName

(

"

p

"

)

;

var

i

;

for

(

i

=

0

;

i

<

myCollection

.

length

;

i

++

)

{

myCollection

[

i

]

.

style

.

backgroundColor

=

"

red

"

;

}

Try it »

Note

An HTMLCollection Is Not an Array!

An HTMLCollection may look like an array, but it is not.

You can use indexes to get elements just like with an array.

An HTMLCollection cannot use array methods: valueOf(), pop(), push(), or join().