0

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

3
  • 1
    That array is an array of strings, not an array of those variables Commented Oct 21, 2017 at 21:32
  • 1
    Replace the strings 'div1' etc. with Pointers div1 Commented Oct 21, 2017 at 21:33
  • Thank you Patrick and Jonas. That did work. Commented Oct 21, 2017 at 21:35

2 Answers 2

3

Remove the quotes like: var myArray = [div1,div2,div3]

Sign up to request clarification or add additional context in comments.

Comments

0

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";  
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.