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) Traversing the DOM Child Traversal

Cian Jochem
Cian Jochem
6,574 Points

why is 'i' not defined?

?

app.js
var section = document.querySelector('section');
var paragraphs = section.children;


for (i = 0; i < paragraphs.length; i++) {
  paragraphs[i].style.backgroundColor = 'blue';
}
index.html
<!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>&copy; 2019</p> 
        </footer>
        <script src="app.js"></script>
    </body>
</html>
Brandon White
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brandon White
Full Stack JavaScript Techdegree Graduate 35,771 Points

I'm actually a bit surprised that your program told you that "i" was undefined. It shouldn't be. Ella's right in that you should include the let keyword when declaring "i" in your for loop, but not including the let keyword does not cause the "i" variable to not be created... it just creates it in the global scope. And so even after the for loop has finished executing, the window would still hold a variable named "i", and it's value would be 3.

The error you received appears to specifically be a Treehouse thing. The test the challenge is using to evaluate your code appears to be making sure that you include the let keyword, which again (is good practice). But it may also be important to understand that in a real world coding situation, you would not get an error for not including let or const before i (or any other variable). It just might cause other issues later in your program.

2 Answers

Because you have not declared it anywhere. In the beginning of you for loop the i has to bee declared using let.

Cian Jochem
Cian Jochem
6,574 Points

thx and sorry for this question...

np, and no need to be sorry for any questions!