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 Interactive Web Pages with JavaScript JavaScript and the DOM Where to Look for Help - Documentation

why is it necessary to add the index value to make this work?

I tried to store the body element in a var for something I was experimenting with. It did not work. I can see here the same thing was done successfully adding the index value[0]. I would love to understand why?

function generate_table() {
  // get the reference for the body
  var body = document.getElementsByTagName("body")[0];

the alternate solution someone gave me was...

document.body.append(ul);

which did work for what I was trying to do

2 Answers

Fábio Nascimento
Fábio Nascimento
10,418 Points

The .getElementsByTagName method returns an array of results, so you get something like '[<body>....</body>]'. To access a value in an array you need its index, that's why.

Thank you

The reason for adding the [0] in the code is because the .getElementsByTagName() method returns an array of all elements with the provided tag name.

An alternative method to use in order to return the first instance of an element would be to use .querySelector("body")

Thank you, that's good to keep in mind also. Many paths, same destination.