简体   繁体   中英

Change Properties of Items using a forEach Method (javascript)

I'm using a javascript forEach method to iterate over items in an array, but it's throwing an error when I try and do something with the items.

In the code below when I console log 'item' it gives the desired behavior of logging 'div1, div2, div3' to the console. However, when I try and make a change to these items it won't allow it. The examples of using a forEach method in JS when you Google it is very abstract.

How do I use this method to change the background colors or other properties of the items?

Codepen link is here https://codepen.io/emilychews/pen/boJBKB

JS

var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
var div3 = document.getElementById('div3');

var myArray = ['div1','div2','div3']

myArray.forEach(function(item){

  console.log(item);

  item.style.backgroundColor = "blue";  

})

CSS

.div {height: 50px; width: 50px; background-color: red; margin-bottom: 10px;}

HTML

<div class="div" id="div1"></div>
<div class="div" id="div2"></div>
<div class="div" id="div3"></div>

Any help would be awesome

Emily

删除像这样的引号: var myArray = [div1,div2,div3]

your myArray contains Strings , not Dom Nodes . try this code:

var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
var div3 = document.getElementById('div3');

var myArray = [div1,div2,div3]

myArray.forEach(function(item){
  console.log(item);
  item.style.backgroundColor = "blue";  
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM