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

Sahan Balasuriya
Sahan Balasuriya
10,115 Points

My background colour doesn't change for even or odd

the red and purple seem to work but not the last nth child selector im not sure what i did wrong.

javascript:

const myList = document.getElementsByTagName('li');

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

//not purple
const notPurple = document.querySelectorAll('.not-purple');

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


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

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

the 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>Making a web page interactive</p>
    <p>Things that are purple</p>
    <ul>
      <li>grapes</li>
      <li class="not-purple">oreo's</li>
      <li>amethyst</li>
      <li>lavender</li>
      <li>plums</li>
    </ul>
    <input type="text" id="myTextInput">
    <button id="myButton">Change Headline color</button>
    <script src="app.js"></script>
  </body>
</html>

1 Answer

Steven Parker
Steven Parker
231,264 Points

All 3 of the loops are all the same:

for (let i = 0; i < myList.length; i +=1) {

But only the first one is working with "myList". The others should be working with "notPurple" and "evens".