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

What Am I Doing Wrong?

How would you select the body element using document.getElementsByTagName, and store it in the variable body?

const body = ?

I thought it would be: const body = document.getElementsByTagName("body");

However, it tells me I'm wrong and I haven't figured a different way. I watched the video again and it looks like that's what he does in the video. Help please!

2 Answers

Joel Bardsley
Joel Bardsley
31,249 Points

The getElementsByTagName() method returns a collection of all elements in the document with the specified tag name, so you'd have to specify the array key [0] to retrieve the body element itself.

Robert Hemfelt
Robert Hemfelt
7,303 Points

But wouldn't const body = document.getElementsByTagName("body"); return the 'collection' of all elements named 'body,' even if it's only 1 element?

Ben Ahlander
Ben Ahlander
7,528 Points

so is it

const body = getElementsByTagName('body[0]')

?

Andy Cruz
Andy Cruz
7,846 Points

This is the answer:

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

Explanation: First: don't forget that getElementsByClassName is a method of "document", so you have to "call" it. Second: getElementsByTagNam will return a HTML collection of items. So later you'll have to specify the item position. Third: between parentheses, you have to specify only the TagName ('body'). Fourth: finally you have to indicate the position of the item in the array [0].