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

Can someone help me out with this question?

the question that says document.getElementsByTagName('body')

1 Answer

David McNeill
David McNeill
44,438 Points

Hi Jyoti,

The hint in the question mentions that getElementsByTagName returns a collection of elements, not a single element. If you know about arrays as collections of elements, you might know about bracket syntax too.

For example:

const myArray = ['item1', 'item2', 'item3'];


This code would log out the first item in the array ('item1') because I'm using [0] to select it. I could use [1] or [2] to log out the others. This is the index of the array element you need to fetch.

So to answer the question correctly, you just need to add [0] to the end of your line of code so it reads:

const body = document.getElementsByTagName("body")[0];

This means you're fetching all of the elements in the DOM that have a tag name of body into a collection, then selecting the first item in that collection. It's a trick question because we know there will only ever be one <body> element! the more likely selector would be document.querySelector('body'), but that will probably appear later in the course.

Hope this helps!