NodeList: forEach()-Methode
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since October 2017.
Please take two minutes to fill out our short survey.
Die forEach()
-Methode der NodeList
Schnittstelle ruft den im Parameter angegebenen Callback einmal für jedes Wertpaar in der Liste in Einfüge-Reihenfolge auf.
Syntax
forEach(callback)
forEach(callback, thisArg)
Parameter
callback
-
Eine Funktion, die für jedes Element von
someNodeList
ausgeführt wird. Sie akzeptiert 3 Parameter:currentValue
-
Das aktuelle Element, das in
someNodeList
verarbeitet wird. currentIndex
Optional-
Der Index des
currentValue
, das insomeNodeList
verarbeitet wird. listObj
Optional-
Die
someNodeList
, auf dieforEach()
angewendet wird.
thisArg
Optional-
Wert, der als
this
beim Ausführen descallback
verwendet wird.
Rückgabewert
Beispiel
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");
Der obige Code führt zu folgendem Ergebnis:
[object HTMLParagraphElement], 0, myThisArg [object Text], 1, myThisArg [object HTMLSpanElement], 2, myThisArg
Spezifikationen
Specification |
---|
DOM # interface-nodelist |