1

How would I use forEach to populate HTML elements? In my simple example below I'm trying to populate each DIV with the counter "increment". I'm using this.innerHTML to target each innerHTML in the array. I know I'm missing something but I can't see it.

var myArray = document.getElementsByClassName('box');
 
myArray = Array.from(myArray);
 
myArray.forEach( (item, increment) => this.innerHTML = increment );
body {
    margin: 0;
    padding: 0;
    font-size: 2rem;
    font-family: arial;
    color: white;
}
 
.box {
    margin: 0 0 10px;
    padding: 10px;
    background-color: blue;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
DR01D
  • 1,245
  • 9
  • 21
  • 2
    Did you mean `item.innerHTML = increment`? – Marty Jul 11 '17 at 06:23
  • 2
    Swap `this` to `item`, as you declare `item` variable for each array element. – Egor Stambakio Jul 11 '17 at 06:24
  • 2
    [`arr.forEach(function callback(currentValue, index, array) {}[, thisArg]);`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach): _"If a `thisArg` parameter is provided to `forEach()`, it will be used as callback's `this` value. Otherwise, the value `undefined` will be used as its this value. The `this` value ultimately observable by `callback` is determined according to the [usual rules for determining the this seen by a function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)."_ – Andreas Jul 11 '17 at 06:26

2 Answers2

2

forEach is passing item and increment as parameters.

this does not refer to your item but to the global window in this scope. You can set the item.innerHTML by using the item parameter.

var myArray = document.getElementsByClassName('box');
 
myArray = Array.from(myArray);
 
myArray.forEach( (item, increment) =>  item.innerHTML = increment} );
body {
    margin: 0;
    padding: 0;
    font-size: 2rem;
    font-family: arial;
    color: white;
}
 
.box {
    margin: 0 0 10px;
    padding: 10px;
    background-color: blue;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
Alexander Higgins
  • 6,101
  • 1
  • 16
  • 35
0

This code will work: when using forEach, the item in the array is the first argument. "this" is the window in this context.

var myArray = document.getElementsByClassName('box');
var arr = Array.from(myArray)
arr.forEach((item,counter)=>(item.innerHTML = counter))
Xingzhou Liu
  • 1,265
  • 6
  • 9