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 Using CSS Queries to Select Page Elements

Hanna Zeif
Hanna Zeif
11,309 Points

Even and Odd do nothing

The code for even and odd doesn't work. I copied it exactly as it appears in the video. The console doesn't return an error; just seems to ignore it.

const evens = document.querySelectorAll('li:nth-child(even)');

for (let i = 0; i < evens.length; i += 1) { evens[i].style.backgroundColor = 'lightgray'; }

And my html: <!DOCTYPE html> <html> <head> <title>JavaScript and the DOM</title> <link rel="stylesheet" href="css/style.css"> </head> <body> <h1 id="myHeading">JavaScript and the DOM</h1> <p title="label">Making a web page interactive</p>

<p>Things that are purple:</p>

<ul> <li>grapes</li> <li class="error-not-purple">oranges</li> <li>amethyst</li> <li class="error-not-purple">fire trucks</li> <li class="error-not-purple">snow</li> <li>lavender</li> <li>plums</li> </ul>

<script src="app.js"></script>

</body> </html>

2 Answers

Steven Parker
Steven Parker
229,732 Points

It works for me, every other list item line has a grey background.

But I'm not using all the code you are. Is there possibly something in the "css/styles.css" file that might be overriding the script? And is the script being loaded (is it in a file named "app.js")?

To facilitate a more complete analysis you can make a snapshot of your workspace and post the link to it here.

Terry Day
Terry Day
1,454 Points

I would probably bet you did the same thing I did. Check your const errorNotPurple = document.querySelectorAll('error-not-purple'); and make sure you add the period before the word error. Once I did that it cleared it up.

const errorNotPurple = document.querySelectorAll('.error-not-purple');

for (let i = 0; i < errorNotPurple.length; i += 1) { errorNotPurple[i].style.color = 'red'; }

const evens = document.querySelectorAll('li:nth-child(even)');

for (let i = 0; i < evens.length; i += 1) { evens[i].style.backgroundColor = 'lightgray'; }