Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript and the DOM (Retiring) Getting a Handle on the DOM Selecting Multiple Elements

What am I doing wrong here?

I am getting this error but not sure what I am doing wrong? - There was an error with your code: TypeError: 'undefined' is not an object (evaluating 'listItems[i].style')

js/app.js
var listItems = listItems = document.querySelectorAll('#rainbow');
var colors = ["#C2272D", "#F8931F", "#FFFF01", "#009245", "#0193D9", "#0C04ED", "#612F90"];

for(var i = 0; i < colors.length; i ++) {
  listItems[i].style.color = colors[i];   
}
index.html
<!DOCTYPE html>
<html>
  <head>
    <title>Rainbow!</title>
  </head>
  <body>
    <ul id="rainbow">
      <li>This should be red</li>
      <li>This should be orange</li>
      <li>This should be yellow</li>
      <li>This should be green</li>
      <li>This should be blue</li>
      <li>This should be indigo</li>
      <li>This should be violet</li>
    </ul>
    <script src="js/app.js"></script>
  </body>
</html>

2 Answers

Martin Balon
Martin Balon
43,651 Points

Hi Emmanuel,

The issue with your code is that you are assigning to variable another variable with the same name and then you are assigning an html element on the same line again. You can't assign twice on the same line and assigning variable to the same variable without changing its value isn't good idea either.

Also you are assigning the ul list to your variable but you need an array or collection of li so you can use for loop to loop through this array and change color of each li. There are few ways how to assign all li inside ul. Have a look below to see an example of two different ways to achieve this.

var listItems = document.getElementsByTagName('li');
var listItems = document.getElementById('rainbow').children;

Thanks