JavaScript JavaScript and the DOM 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

Lukas Schmid
Lukas Schmid
6,999 Points

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!