Web IDL 既定の NodeList.prototype.forEach
の Polyfill(互換コード)を提供します。
NodeList の index 0 から順番に走査し、第一引数に指定されたコールバック関数を呼び出し、反復処理を行います。 コールバック関数の仮引数には第一引数「現在の要素ノード」、第二引数「現在のインデックス値」、第三引数「NodeListオブジェクト」が渡されます。
document.querySelectorAll('.foo').forEach(function (element, i, nodeList) {
console.log(element); // nodeList[0] -> nodeList[1] -> nodeList[2] -> ...
console.log(i); // 0 -> 1 -> 2 -> ...
console.log(nodeList); // document.querySelectorAll('.foo') の返り値
});
第二引数でコールバック関数内の this
値を指定することが出来ます(オプション)。
document.querySelectorAll('.foo').forEach(function (element, i, nodeList) {
console.log(this); // {a: 1}
}, {a: 1});
NodeList.prototype.forEach
は Array.prototype.forEach
とは違い、列挙可能(enumerable: true)な仕様です。従って、NodeList
を for-in
で走査すれば、列挙されます。
var nodeList = document.querySelectorAll('.foo'), keys = [];
for(var key in nodeList) {
keys.push(key);
}
console.log(JSON.stringify(keys)); // ["0","1","2","3","4","5","6","7","length","item","entries","forEach","keys","values"]