DOM

HTMLCollection.item() メソッド

 編集:2022.10.27 by T.A.

[Edge]。→

HTMLCollection の、指定されたオフセットにあるノード Nodeを返します。

mdn: 指定されたオフセットにあるノードをコレクションに返します。

mdn: 注: HTMLCollection のコンテンツはライブであるため、基になるDOMを変更すると、コレクション内の個々のノードの位置が変更される可能性があります。そのため、特定のノードのインデックス値は必ずしも一定ではありません。

構文
HTMLCollection.item(index)
HTMLCollection HTMLCollection オブジェクト。
index 返されるノードの位置を表す数値。

HTMLCollection の要素は、document のソースに表示されるのと同じ順序で表示されます。

戻り値

指定されたインデックスの Node。インデックスがゼロ未満または length プロパティ以上の場合は null。

使用上の注意

item() メソッドは、HTMLCollection から番号付きの要素を返します。JavaScript では、HTMLCollection を配列として扱い、配列表記を使用してインデックスを作成する方が簡単です。以下の例を参照してください。

mdnより
var c = document.images;  // This is an HTMLCollection
var img0 = c.item(0);     // You can use the item() method this way
var img1 = c[1];          // But this notation is easier and more common

HTML:

<SPAN class=Test>SPAN要素。<B class=Test>B要素</B></SPAN><BR class=Test>
<DIV class=Test>DIV要素</DIV>
<INPUT class=Test><BR>

JavaScript:

HC=document.getElementsByClassName("Test");  //class 名「Test」のコレクションを得る。
D="";
for(I=0; I<HC.length; I++){  //タグ名を表示させる:
//  D=D+HC[I].tagName+"、";
  D=D+HC.item(I).tagName+"、";
}

Dは、「SPAN、B、BR、DIV、INPUT、」

HTMLCollection:HC は、

=[object]:[object HTMLCollection]
0=[object]:[object HTMLSpanElement]
1=[object]:[object HTMLElement]
2=[object]:[object HTMLBRElement]
3=[object]:[object HTMLDivElement]
4=[object]:[object HTMLInputElement]
length=[number]:5
item=[function]:function item() { [native code] }
namedItem=[function]:function namedItem() { [native code] }

document.getElementsByClassName()


テスト