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 trialWilliam Mackay
25,189 PointsWhat 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
31,249 PointsThe 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.
Andy Cruz
7,846 PointsThis 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].
Robert Hemfelt
7,303 PointsRobert Hemfelt
7,303 PointsBut wouldn't const body = document.getElementsByTagName("body"); return the 'collection' of all elements named 'body,' even if it's only 1 element?
Ben Ahlander
7,528 PointsBen Ahlander
7,528 Pointsso is it
const body = getElementsByTagName('body[0]')
?