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.


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';

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>
    <title>JavaScript and the DOM</title>
    <link rel="stylesheet" href="css/style.css">
    <h1 id="myHeading">JavaScript and the DOM</h1>
    <p>Making a web page interactive</p>
    <p>Things that are purple</p>
      <li class="not-purple">oreo's</li>
    <input type="text" id="myTextInput">
    <button id="myButton">Change Headline color</button>
    <script src="app.js"></script>

1 Answer

Steven Parker
Steven Parker
205,159 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".