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!

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

Why do we need a for loop for change the h2 elements?

Why do we need a for loop for change the h2 elements?

4 Answers

The question asked, "Select all the <h2> elements in the document." "ALL" h2 elements You can use 'querySelectorAll' in place of 'getElementsByTagName'. They'll both work the same.

There may be more than one. The getElementsByTagName() method used in the video returns a collection of elements. The for loop is used to iterate over the collection.

Marvin Müller
Marvin Müller
8,884 Points

Yea I also was iritated by the fact that you can't just use document.querySelectorAll() xD Anyone can describe why that is?

There are more than one <h2> elements. He used getElementsByTagName('h2') to get all headers. since there are more than one <h2> tags found and he wants to change all <h2> tag, he used for loop to iterate through all <h2> tags found by getElementsByTagName('h2').

Marvin Müller document.querySelectorAll() is a CSS Selector, it only finds all elements in a document that has a specific css. for example: document.querySelectorAll('.example'); it will get all elements that has class of 'example' on their HTML tag.

<p class = 'example'>Example paragraph </p> <h1 class = 'example'>Example Header 1</h1> <h2 class = 'h2sample'>Example Header 2</h2> <-- this is not included since it has a different class of CSS

You need to use a for loop because the querySelectorAll() returns a collection of html elements which is an array. You have to iterate through each element in the array and individually set each property for the code to work. Imagine trying to set an array of strings to a single string value, it doesn't really make sense right?