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 One Solution

Kishan P
Kishan P
9,921 Points

need help with the second question?

// 2: Select all the <h2> elements in the document.
//    Set the color of the <h2> elements to a different color.
const h2  = document.getElementsByTagName ('h2');
  h2.style.border = "2px solid red";

Why does the instructor using for loop and why can't i use this to change the color?

1 Answer

Michael Williams
Michael Williams
Courses Plus Student 8,059 Points

It's because const h2 = document.getElementsByTagName ('h2'); returns an array-like object. They key giveaway here is that elements is plural. So you know it's going to return more than one element and store them like an array.

Therefore, you need a loop to iterate over each one to change it. Otherwise, it won't know which one to change.

Hope this helps!

Does this apply to querySelectorAll as well? I keep getting an undefined error when I try that method (without the loop) as opposed to querySelector which works fine at grabbing the first occurrence.

edit: found the answer myself. I would need to iterate over all for querySelectorAll