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

Jake Kobs
Jake Kobs
9,215 Points

Would this be a simpler way of going at the non-purple items on the list?

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

for(let i = 0; i < purpCol.length; i++){
  if(purpCol[i].className == "notPurp"){
    purpCol[i].style.color = "red";
  } else {
  purpCol[i].style.color = "purple"; 
  }
}

1 Answer

Steven Parker
Steven Parker
231,248 Points

Unless you also change the HTML, you'd need to look for the class "error-not-purple" instead of "notPurp".

But otherwise, the idea of using a single loop to color both kinds of items is a bit more efficient. :+1:

And if you're familiar with the ternary operator and "for...of" you can simplify it a bit more:

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

for (let li of myList) {
  li.style.color = li.className == "error-not-purple" ? "red" : "purple";
}
Jake Kobs
Jake Kobs
9,215 Points

Awesome! How long have you been coding for? You make JavaScript seem so simple. Maybe I just think it's difficult because I started learning about it 3 days ago :P

Steven Parker
Steven Parker
231,248 Points

For 3 days, your progress is amazing! :tada: I've been coding JavaScript on a regular basis for about 5 years.

Jake Kobs
Jake Kobs
9,215 Points

Thank you, Steven! It's nice when you're finally able to conceptualize the areas in which JavaScript excels pertaining to user interactions. In your opinion, how much knowledge do you need in JavaScript before you can start applying for jr. dev jobs? I also have an associates in Computer Science and Information Systems if that makes a difference lol

Steven Parker
Steven Parker
231,248 Points

Depending on the job, a comfortable familiarity might be all you need at first, particularly if your CSS skills are strong.