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 trialBiruktawit Galoro
Front End Web Development Techdegree Graduate 12,661 Pointsselecting 'body' by document.getElementsByTagName
const body = document.getElementsByTagName(body)[0]; is the right anwer for the question ' How do you select the body' by document.getElementsByTagName?' in the quiz. I get it until (body) but what is the purpose of [0] in here. we are just selecting the whole 'body' why don't we just write const body = document.getElementsByTagName(body); and finish the code here?
3 Answers
Zaid Khan
12,769 PointsNo, it's storing the body element from the whole HTML Collection
Zaid Khan
12,769 PointsBecause document.getElementsbyTagName
will return a list of elements and not a single element.
Even if there is only one element with that tag name it will be in a Node List which is why you have to use the [0] to get the particular one.
I recommend open the console of any webpage and type const body = document.getElementsbyTagName('body');
then console.log(body)
it will return the whole HTML Collection but if you will const body = document.getElementsbyTagName('body')[0];
and then console.log(body)
it will return the exact body element.
Biruktawit Galoro
Front End Web Development Techdegree Graduate 12,661 Pointsi got that but in this 'How would you select the body
element using document.getElementsByTagName, and store it in the variable body?
(Hint: Don't forget that this method returns a zero-based collection, not a single element.) question what is zero-based collection mean? does [0] representing the index? if it is why we don't use another index beside 0?
Zaid Khan
12,769 PointsLike this:
document.getElementsByTagName('body')[0];
It's been stored in const body
Biruktawit Galoro
Front End Web Development Techdegree Graduate 12,661 Pointsso its storing the first body element right?
Biruktawit Galoro
Front End Web Development Techdegree Graduate 12,661 PointsBiruktawit Galoro
Front End Web Development Techdegree Graduate 12,661 Pointsoh i see. thanks for your time. I get it now.