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

Odd error with changing color

I am following along with the video regarding changing color of <li>s in an <ul>.

My goal:

  1. create a list with 8 entries (all say "something").
  2. have all entries turn purple with getElementsByTagName(li)
  3. have the 3rd and 6th entry turn red with getElementByClassName("error-not-purple")

My results:

The first two items are displaying red. The remaining 6 items are displaying purple.

I can not figure out why it is making the first two red when it shouldn't even be looking at those two.

HTML Code

<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript and the DOM</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <h1 id="myHeading">JavaScript and the DOM</h1>
    <p>Making a web page interactive</p>
    <ul>
        <li>something</li>
        <li>something</li>
        <li class="error-not-purple">something</li>
        <li>something</li>
        <li>something</li>
        <li class="error-not-purple">something</li>
        <li>something</li>
        <li>something</li>
    </ul>
    <script type="text/javascript" src="script.js"></script>
  </body>
</html>

JS Code

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

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

const   errorNotPurple = document.getElementsByClassName("error-not-purple");

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

1 Answer

You are using the incorrect array when you want to change the elements to red.

myList[i].style.color="red"; #This should use errorNotPurple

Derp. Thanks for the correction!