DOMTokenList.forEach()
The forEach()
method of the DOMTokenList
interface calls the callback given in parameter once for each value pair in the list, in insertion order.
Syntax
tokenList.forEach(callback [, thisArg]);
Parameters
callback
-
Function to execute for each element, eventually taking three arguments:
currentValue
-
The current element being processed in the array.
currentIndex
-
The index of the current element being processed in the array.
listObj
-
The array that
forEach()
is being applied to.
-
thisArg
Optional -
Value to use as
this
when executingcallback
.
Return value
Example
In the following example we retrieve the list of classes set on a <span>
element as a DOMTokenList
using Element.classList
. We when retrieve an iterator containing the values using forEach()
, writing each one to the <span>
's Node.textContent
inside the forEach()
inner function.
HTML
<span class="a b c"></span>
JavaScript
let span = document.querySelector("span"); let classes = span.classList; let iterator = classes.values(); classes.forEach( function(value, key, listObj) { span.textContent += `${value}${key}/${this} ++ `; }, "arg" );
Result
Polyfill
This polyfill adds compatibility to all Browsers supporting ES5:
if (window.DOMTokenList && !DOMTokenList.prototype.forEach) { DOMTokenList.prototype.forEach = function (callback, thisArg) { thisArg = thisArg || window; for (var i = 0; i < this.length; i++) { callback.call(thisArg, this[i], i, this); } }; }
Specifications
No specification data found for api.DOMTokenList.forEach
.
Check for problems with this page or contribute a missing spec_url
to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.
Browser compatibility
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
forEach |
42 |
16 |
50 |
No |
32 |
10.1 |
45 |
45 |
50 |
32 |
10.3 |
5.0 |
See also
-
DOMSettableTokenList
(object that extends DOMTokenList with settable .value property)
© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/forEach