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 trialSAMUEL LAWRENCE
Courses Plus Student 8,447 PointsWhat's wrong with this question?
Hi guys, in the Selecting Elements with the Same Class Name
Quiz,
one of the questions were,
How would you select the body element using the document.getElementsByTagName
, and store it in the variable body
?
Hint: Donβt forget that this method returns a collection, not a single element.
const body = _______________
I wrote ;
const body = document.getElementsByTagName('body');
but got that as a wrong answer. What am I missing?
FYI when I ran this code in my text editor I didn't get any errors. Why is it a wrong answer here?
1 Answer
andren
28,558 PointsAs the question's hint points out the getElementsByTagName
method returns a collection of elements, it does not return a specific element. This is the case even if there is only one element matching the tag you pass into it.
That means that your code stores a collection of HTML elements in the body
constant rather than storing the body
element itself. To pull out the body
element you can use standard bracket notation like you would do on an array.
Like this:
const body = document.getElementsByTagName('body')[0]; // Pull out the HTML element at index 0
That would pull out the first element in the collection, which will be the body
element itself.
SAMUEL LAWRENCE
Courses Plus Student 8,447 PointsSAMUEL LAWRENCE
Courses Plus Student 8,447 PointsNice one. Thanks. The thought crossed my mind but didn't do it.