JavaScript JavaScript and the DOM Traversing the DOM Child Traversal

Spencer Mendoza
Spencer Mendoza
5,670 Points

How do I use a loop to change the color of elements within a variable?

Whenever I run this code it says that task 1 is no longer passing (task one was to assign all the child elements of 'section' to the variable 'paragraphs'). I haven't even touched that code but it passes every time I go back.

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

for (i = 0; i < paragraphs.length; i += 1) {
  paragraphs[i].style.Color = '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; 2016</p> 
        </footer>
        <script src="app.js"></script>
    </body>
</html>
Erick R
Erick R
5,083 Points

Try to initialize the For loop variable i.

for(let i = 0; i < paragraphs.length; i += 1) {
............
............
}
for( var i = 0; i < paragraphs.length; i += 1) {
.......................
................
}

Also apart from i not being initialized, style.color should be lower case as mentioned by Olga.

4 Answers

Olga Díaz Cerezo
Olga Díaz Cerezo
8,681 Points

Hi Spencer. You have to write style.color all in small caps.

Steven Parker
Steven Parker
98,159 Points

I think you meant "lower case". The term "small caps" is a visual effect that does not occur in code.

Olga Díaz Cerezo
Olga Díaz Cerezo
8,681 Points

Sorry, I meant "lower case", as Steven says. Thank you for the correction! :)

Steven Parker
Steven Parker
98,159 Points

That message can be confusing until you know that any syntax error invalidates the entire script, so the re-checks of the previous tasks fail.

In this case, the syntax error is caused by a missing declaration (with "var" or "let") of the loop variable. The actual error was: "ReferenceError: Strict mode forbids implicit creation of global property 'i'"

You also have a spelling error where you wrote "Color" (with a capital "C") instead of "color" (lower case "c").

Spencer Mendoza
Spencer Mendoza
5,670 Points

thanks guys, I just had to initialize the i variable with 'let'. Color was capitalized because I had it set as 'backgroundColor' before I realized that wasn't what I was trying to do lol.

Steven Parker
Steven Parker
98,159 Points

Spencer Mendoza — Glad to help. You can mark the question solved by choosing a "best answer".
And happy coding!