Reputation: 1365
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>
Upvotes: 1
Views: 1123
Reputation: 1559
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))
Upvotes: 0
Reputation: 6923
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>
Upvotes: 2