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

HTMLCollection item() method

HTMLCollection item() method

DOM HTMLCollection Object Reference DOM HTMLCollection


Definition and Usage

The item() method returns the element at the specified index position in the HTMLCollection object.

The order of elements in the HTMLCollection object is the same as their order in the document source code, and the index starts at 0.

You can also use the following shorthand way, and the result obtained is the same:

var x = document.getElementsByTagName("P")[0];

Syntax

HTMLCollection.item(index)

Or:

HTMLCollection[index]

Parameters Type Description
index Number Required. The index value of the element.
 **注意:** 起始位置为0,最后一位元素索引为 HTMLCollection.length-1,index 需要在这个范围内。 |


Browser support

Method
item() Yes Yes Yes Yes Yes

Example

Example

Modify the HTML content of the first p element:

document

.

getElementsByTagName

(

"

P

"

)

.

item

(

0

)

.

innerHTML

=

"

Paragraph modified

"

;

Try it »

Example

Loop through and output all elements with class="myclass" and modify their background color:

var

x

=

document

.

getElementsByClassName

(

"

myclass

"

)

;

for

(

i

=

0

;

i

<

x

.

length

;

i

++

)

{

x

.

item

(

i

)

.

style

.

backgroundColor

=

"

red

"

;

}

Try it »

Example

Get the HTML content of the first p element and insert it into the div element:

var

div

=

document

.

getElementById

(

"

myDIV

"

)

;

var

x

=

div

.

getElementsByTagName

(

"

P

"

)

.

item

(

0

)

.

innerHTML

;

Try it »


Related Articles

HTMLCollection: length property

HTML Element: getElementsByClassName() Method

HTML Element: getElementsByTagName() Method


DOM HTMLCollection Object Reference DOM HTMLCollection