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 trialAsh M
742 PointsI'm trying to loop through a color array and apply the colors to each list item in a ul. My code isn't working.
So I’m stuck and am having trouble figuring out where I’m making the mistake. The code isn't running properly.
The code is supposed to loop through each list item and apply the proper color from the colors array.
The question asks to set the variable listItems to refer to a collection. The collection will contain all list items in the ul with the id ‘rainbow’.
Here’s the 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>
and then here’s the js:
const listItems = document.getElementById('rainbow');
const colors = ["#C2272D", "#F8931F", "#FFFF01", "#009245", "#0193D9", "#0C04ED", "#612F90"];
for(var i = 0; i < colors.length; i ++) {
listItems[i].style.color = colors[i];
}
<!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>
const listItems = document.getElementById('rainbow');
const colors = ["#C2272D", "#F8931F", "#FFFF01", "#009245", "#0193D9", "#0C04ED", "#612F90"];
for(var i = 0; i < colors.length; i ++) {
listItems[i].style.color = colors[i];
}
3 Answers
james south
Front End Web Development Techdegree Graduate 33,271 Pointsthe rainbow id is only the unordered list, not the list items inside it. to reach the list items in rainbow you need to extend what you have with another selector method. you can chain method calls together with dots, so object.method1().method2() etc.
Ash M
742 PointsIt worked :) thanks for your help
Otto linden
5,857 PointsHow did you do it? I tried it like this:
let listItems = document.getElementById('rainbow').getElemntsByTagName('li');