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) Making Changes to the DOM Appending Nodes

Why was it neccessary to write index 0 after getElementsByTagName in this case?

.

3 Answers

Tyler Halstead
Tyler Halstead
7,987 Points

in addition to what Jesse said, you could use querySelector to omit using the index. I'm guessing Guil wanted to show that if we had multiple ul elements, we could select which one to target using an index, so if you had a second ul element you could target it with [1].

Clayton Perszyk
MOD
Clayton Perszyk
Treehouse Moderator 48,723 Points

It returns a collection of objects as a NodeList object (which is similar to an array) and you use index 0 to grab the first element in the list. So you use index when you want to access a specific element.

.

Try it out if you want. From my experience it doesn't work, for the same reason that it wouldn't work with an array. This is because when targeting a collection (or array), you are essentially targeting a container, but not the contents of it. The computer isn't going to reason "oh, maybe Amandeep wanted me to grab the content of the box, since there is only one item in there, and humans like contents of boxes more than boxes themselves." Since the program isn't going to think outside of the box (hehehe), you gotta tell it to not only open up the box, but to grab the content as well!