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

honesty, i dont know why this for loop not working

trying to experiment from back to front with button color. the code looks good to me but no worky worky?

<button class="classBn">colour red</button>
<button>no colour</button>
<button class="classBn">colour red</button>
<button class="classBn">colour red</button>
  const classB = document.getElementsByClassName(`classBn`);

  for (let i = classB.length; i >= 0; i--) {
    classB[i].style.color = `red`;
  };

1 Answer

Robert Stefanic
Robert Stefanic
35,170 Points

The problem is with this line:

  for (let i = classB.length; i >= 0; i--) {

Think about what classB.length will return. It returns the length of the array, not the last index of the array.

So when you're assigning i to classB.length, i has a value of 3, but classB[3] is undefined. Arrays start at 0 in JS, so the indexes of your array are 0, 1, and 2.

thank you sir. that makes sense to me, i now added a minus 1 for i and it works perfectly.