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

Can someone explain this piece of code for me..? (JS and the DOM)

let navigationLinks = document.getElementsByTagName("nav")[0].getElementsByTagName("a");

I understand the first part of the code, selecting the nav tag by using the selector.

I DONT understand why I then need to add the index position ( [0] ) after it.

I also guess putting the second selector directly after the first you're telling it to find the first then go inside it?

Would I not just be able to write.. document.querySelectorALL('nav > a');

Any insight is appreciated!

1 Answer

Steven Parker
Steven Parker
231,126 Points

The getElementsByTagName function returns an element collection and not just a single element. The [0] indexing is required to then select the first element from the collection. In this case it also happens to be the only element in the collection but it still needs to be selected to then apply the next element-based operation on it.

You are quite right that you can get the same result with a single operation, though a more accurate translation would use a descendant selector instead of direct child selector:

let navigationLinks = document.querySelectorAll('nav a');

This makes clear sense, thanks for the response Steven Parker