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 trialKevin S
Data Analysis Techdegree Student 15,862 PointsWhy does my code not change the color to blue here
Hi all,
why doesn't my code work? See the comments for an explanation of what I think is happening at each step.
Thanks!
Kevin
const section = document.querySelector('section'); // targets the element section
let paragraphs = section.children; // targets all the p tags
for (i = 0; i < paragraphs.length; i+=1) { // iterator starts at 0 and goes up by 1 until it reaches and completes its action on the last elemnt
paragraphs[i].style.color = 'blue'; // targets the first p element only and adds the color blue then moves on to the next one as per i+=1
}
<!DOCTYPE html>
<html>
<head>
<title>Child Traversal</title>
</head>
<body>
<section>
<p>This is the first paragraph</p>
<p>This is a slightly longer, second paragraph</p>
<p>Shorter, last paragraph</p>
</section>
<footer>
<p>© 2016</p>
</footer>
<script src="app.js"></script>
</body>
</html>
3 Answers
Justin Cantley
18,068 PointsAssuming that you define "works" by changing the color of all the paragraphs to blue, your code works just fine. I ran it myself with no issue.
Ross King
20,704 PointsHi Kevin,
I'll be honest that I haven't been doing code challenges for a while but this challenge seems to be running in strict mode.
Strict mode forbids implicit creation of global property 'i'. You need to provide the var or let keyword for the i in your loop.
// let i = 0
for (let i = 0; i < paragraphs.length; i += 1) {
paragraphs[i].style.color = 'blue';
}
Jennifer Nordell
Treehouse TeacherKevin Shields Hi there! You're doing terrific and I agree with Justin Cantley that your code works. However, this does come with one major exception. The code must be run not using "strict mode". In many of these challenges, even if you cannot see it, the challenge itself is run with "strict mode" turned on. This means (among other things), that your variables must all be declared. This includes the i
variable in your for
loop.
So where you have this:
for (i = 0; i < paragraphs.length; i+=1)
You should have:
for (let i = 0; i < paragraphs.length; i+=1)
Hope this helps!