aboutsummaryrefslogtreecommitdiff
path: root/files/fr/web/api/nodelist/foreach/index.md
blob: 77666b9e3dfb5c2bab464853e0a41d5fc01baf35 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
---
title: NodeList.prototype.forEach()
slug: Web/API/NodeList/forEach
translation_of: Web/API/NodeList/forEach
browser-compat: api.NodeList.forEach
---
{{APIRef("DOM")}}

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

## Syntaxe

    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` {{Optional_inline}}
  - : Valeur à utiliser comme {{jsxref("this")}} lors de l'exécution du `callback` (_rappel_).

### Valeur retournée

{{jsxref('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 {{Glossary("Polyfill","polyfill")}} ajoute une compatibilité à tous les navigateurs prenant en charge [ES5](https://caniuse.com/#search=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

{{Specifications}}

## Compatibilité des navigateurs

{{Compat}}

## Voir aussi

- {{domxref("Node")}}
- {{domxref("NodeList")}}