DOMTokenList: forEach() method
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.
TheforEach() method of theDOMTokenList interfacecalls the callback given in parameter once for each value pair in the list, ininsertion order.
In this article
Syntax
forEach(callback)forEach(callback, thisArg)Parameters
callbackThe function to execute for each element, eventually taking three arguments:
currentValueThe current element being processed in the array.
currentIndexThe index of the current element being processed in the array.
listObjThe array that
forEach()is being applied to.
thisArgOptionalThe value to use as
thiswhen executingcallback.
Return value
None.
Example
In the following example we retrieve the list of classes set on a<pre> element as aDOMTokenList usingElement.classList. We when retrieve an iterator containing the valuesusingforEach(), writing each one to the<pre>'sNode.textContent inside theforEach() inner function.
HTML
<pre></pre>JavaScript
const pre = document.querySelector("pre");const classes = pre.classList;const iterator = classes.values();classes.forEach(function (value, key, listObj) { pre.textContent += `(${value} ${key})/${this}\n`;}, "arg");