NodeList: forEach() メソッド
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2017年10月.
forEach() は NodeList インターフェイスのメソッドで、引数に渡されたコールバックを、リストのそれぞれの値のペアに対して 1 度ずつ挿入順に呼び出します。
構文
js
forEach(callback)
forEach(callback, thisArg)
引数
callback-
someNodeListの各要素に対して実行する関数です。3 つの引数を受け付けます。currentValue-
現在
someNodeListで処理されている要素です。 currentIndex省略可-
現在
someNodeListで処理されているcurrentValueのインデックスです。 listObj省略可-
forEach()を適用しようとしているsomeNodeListです。
thisArg省略可-
callback内でthisとして使う値です。
返値
例
js
const node = document.createElement("div");
const kid1 = document.createElement("p");
const kid2 = document.createTextNode("hey");
const kid3 = document.createElement("span");
node.appendChild(kid1);
node.appendChild(kid2);
node.appendChild(kid3);
const list = node.childNodes;
list.forEach(function (currentValue, currentIndex, listObj) {
console.log(`${currentValue}, ${currentIndex}, ${this}`);
}, "myThisArg");
上記のコードの結果は以下のようになります。
[object HTMLParagraphElement], 0, myThisArg [object Text], 1, myThisArg [object HTMLSpanElement], 2, myThisArg
仕様書
| Specification |
|---|
| DOM> # interface-nodelist> |
ブラウザーの互換性
Loading…