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) Responding to User Interaction Event Delegation

document.getElementsByTagName('section')[0] - why is '[0]' needed?

Hi all!

I understand that the index [0] takes the first item, but the section tag has multiple children and for this challenge we target the inputs.

I got the answer to this challenge, but its just not clear to me why [0] has to be included since we dont take the first child as [0] in this case is h1 (I may got myself confused here).

Can anyone explain please?

Thanks!

1 Answer

Hi Kevin,

When you use document.getElementsByTagName('section'), you get back a collection of "section"-elements.
So with document.getElementsByTagName('section')[0], you are only pointing to the first section element. But not to its children. There you are referring to the actual section element, not to a child. If you want to go one step deeper to the children, you need to specify and add it.

There are a lot of different ways but just some examples:

document.getElementsByTagName('section') = gives you a collection of all section elements
document.getElementsByTagName("Section")[0] = gives you the first selection element of this collection
document.getElementsByTagName("Section")[0].children = gives you a collection of all children from the first section element
document.getElementsByTagName("Section")[0].children[0] = Gives you the first child of the first section element document.getElementsByTagName("Section")[0].children[1] = Gives you the second child of the first section element.
document.getElementsByTagName("Section")[0].lastChild = Gives you the last child of the first section element
document.getElementsByTagName("Section")[2].children[1] = Gives you the second child of the third section element.

Hope that clears some things up :)

Hi Lukas!

This is an awsome explanation, thank you!