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) Getting a Handle on the DOM Selection Review

selecting 'body' by document.getElementsByTagName

const body = document.getElementsByTagName(body)[0]; is the right anwer for the question ' How do you select the body' by document.getElementsByTagName?' in the quiz. I get it until (body) but what is the purpose of [0] in here. we are just selecting the whole 'body' why don't we just write const body = document.getElementsByTagName(body); and finish the code here?

3 Answers

No, it's storing the body element from the whole HTML Collection

oh i see. thanks for your time. I get it now.

Because document.getElementsbyTagName will return a list of elements and not a single element.

Even if there is only one element with that tag name it will be in a Node List which is why you have to use the [0] to get the particular one.

I recommend open the console of any webpage and type const body = document.getElementsbyTagName('body'); then console.log(body) it will return the whole HTML Collection but if you will const body = document.getElementsbyTagName('body')[0]; and then console.log(body) it will return the exact body element.

i got that but in this 'How would you select the body element using document.getElementsByTagName, and store it in the variable body?

(Hint: Don't forget that this method returns a zero-based collection, not a single element.) question what is zero-based collection mean? does [0] representing the index? if it is why we don't use another index beside 0?

Like this:

document.getElementsByTagName('body')[0];

It's been stored in const body

so its storing the first body element right?