JavaScript JavaScript and the DOM 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
203,163 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".