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 Selecting Elements with the Same Class Name

Color not changing getting error Uncaught TypeError: Cannot read property 'style' of undefined at app.js:5

I am not sure as to why it keeps showing the error I don't see any typos and I have already looked at other questions from community. It wont change to red.

const myList = document.getElementsByTagName('li');
const errorNotPurple = document.getElementsByClassName('error-not-purple');

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

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

This is the html page

<!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="error-not-purple">oranges</li>
      <li>lavender</li>
       <li class="error-not-purple">fire trucks</li>
       <li class="error-not-purple">snow</li>
      <li>plums</li>
    </ul>
    <script src="app.js"></script>
  </body>
</html>

1 Answer

Hi emmanuel egunjobi, I hope you found the answer. I'm a bit late but I'm going to answer it anyway. In your condition, the 0 Is always going to be less than the length of that element. So the loop is looping more than the length of the element. When the loop goes for more than the length of the element, for example errorNotPurple[3].style. It returns an error (a TypeError) because it's basically this undefined.style. What you should do is this:

const myList = document.getElementsByTagName('li');
const errorNotPurple = document.getElementsByClassName('error-not-purple');


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



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