Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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?


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!