NodeList.prototype.forEach()

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.

La méthode forEach() de l'interface NodeList appelle le rappel donné en paramètre une fois pour chaque paire de valeurs dans la liste, dans l'ordre d'insertion.

Syntaxe

js
nodeList.forEach(callback[, thisArg]);

Paramètres

callback

Fonction à exécuter pour chaque élément, contenant éventuellement 3 arguments :

currentValue

L'élément en cours de traitement dans la NodeList.

currentIndex

L'index de l'élément en cours de traitement dans la NodeList.

listObj

L'objet NodeList auquel forEach() est appliqué.

thisArg Facultatif

Valeur à utiliser comme this lors de l'exécution du callback (rappel).

Valeur retournée

undefined (indéfini).

Exceptions

Aucune.

Exemple

js
var node = document.createElement("div");
var kid1 = document.createElement("p");
var kid2 = document.createTextNode("hey");
var kid3 = document.createElement("span");

node.appendChild(kid1);
node.appendChild(kid2);
node.appendChild(kid3);

var list = node.childNodes;

list.forEach(function (currentValue, currentIndex, listObj) {
  console.log(currentValue + ", " + currentIndex + ", " + this);
}, "myThisArg");

résultat :

[object HTMLParagraphElement], 0, myThisArg
[object Text], 1, myThisArg
[object HTMLSpanElement], 2, myThisArg

Polyfill

Ce polyfill ajoute une compatibilité à tous les navigateurs prenant en charge ES5 :

js
if (window.NodeList && !NodeList.prototype.forEach) {
  NodeList.prototype.forEach = function (callback, thisArg) {
    thisArg = thisArg || window;
    for (var i = 0; i < this.length; i++) {
      callback.call(thisArg, this[i], i, this);
    }
  };
}

Spécifications

Specification
DOM
# interface-nodelist

Compatibilité des navigateurs

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

Voir aussi