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

How is this the wrong answer to the question?

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

const body = document.getElementsByTagName('body');

6 Answers

Chris Shaw
Chris Shaw
26,676 Points

Hi Yeshaya Coffman,

When using getElementsByTagName we have to remember that it returns an HTML Collection rather than a single Element like getElementById, because of this we need to select the first item in the collection.

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

Your answer was correct except for missing the item selection.

Happy coding!

But I don't always have to do it or I?

Chris Shaw
Chris Shaw
26,676 Points

When using getElementsByTagName you always have to select an item in the collection, an alternate way of accessing the body element is to use the below.

const body = document.body;

Hope that helps

thanks

Robert Hemfelt
Robert Hemfelt
7,303 Points

In the example they don't select 1 item from the array, they use:

const myList = document.getElementsByTagName('li');

which I assume selects all <li> elements.

Wouldn't const body = document.getElementsByTagName('body'); just select all body elements (even though there's only 1)?

Chufan Xiao
Chufan Xiao
18,955 Points

that's awesome. thx

I agree with Ben Herro: 'Should the question not be 'How would you select the FIRST body element'? It's worded confusingly.'

Although, unlike an <li> or <p>, I've never seen more than one <body> this question is not very good.?

Should the question not be 'How would you select the FIRST body element'? It's worded confusingly.

Markus Mรถnch
Markus Mรถnch
16,383 Points

but they dont do that before in the course with the li element

Yeah, I had the same question. The quiz should say what's wrong.

jiwan gurung
jiwan gurung
4,248 Points

but why we need to give an index number to the body?body is not an array is it?

Chris Shaw
Chris Shaw
26,676 Points

As explained in my original post, the getElementsByTagName method returns an HTML Collection. Specifying an index allows us to get the first element from the collection.

This isn't specific to the body element, it applies to any selector we use on this method.

your answer is correct. I have the same answer and it worked out fine.