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

How does button[0] know that we are referring to the first button element? Is there some implicit numbering in HTML ?

Is the first button element automatically assigned to index 0 in some kind of array of buttons within the document object?

This is in Reference to the "Defining Variables with let and const" exercise.

2 Answers

Steven Parker
Steven Parker
243,318 Points

You're right, a collection of elements (buttons, in this case) will contain them in the order that they occur in the document. So the item with index 0 will be the first element of that type found in the document.

It depends on the context

var mybuttons = document.getElementsByTagName("button") mybuttons[0] // first button

notice the plural "elements", so it returns an array, however something like

var buttonID = document.getElementById("buttonID")

notice the no plural "element" for buttonID,this returns the first match, so the same element would be written as just buttonID ,without referencing an array index

another way of writing it is

document.querySelector("button") //first button

document.querySelectorAll("button") [0] // All buttons so again the first button needs to be referenced as [0]