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 July 2015.

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

js
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 in someNodeList verarbeitet wird.

listObj Optional

Die someNodeList, auf die forEach() angewendet wird.

thisArg Optional

Wert, der als this beim Ausführen des callback verwendet wird.

Rückgabewert

Beispiel

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");

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

Browser-Kompatibilität

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
forEach

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

Siehe auch