Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Interactive Web Pages with JavaScript Selecting Elements and Adding Events with JavaScript Selecting Elements

Riya Chatterjee
Riya Chatterjee
7,582 Points

What do they mean?

What do they mean when they say "use the index(1)"? I'm kind of confused, because I know that the document.getElementsByTagName(); is right, but it's not working. Can someone please help? Thanks.

1 Answer

Erik McClintock
Erik McClintock
45,783 Points


EDIT: If you're referring to the second task of the challenge, then what we need to do is break down what's happening when you use the .getElementsByTagName() method:

Using that method returns an array for you to iterate over, and values that are stored in arrays are able to be referenced by what is called their "index" value, which means "their position in the array". We then need to keep in mind that arrays are indexed starting at zero and increment upwards, meaning that the first item in an array can be found at the 0 index, the second item can be found at the 1 index, the third item is found at the 2 index, and so on.

To reference an item in an array by its index value, we write the name of the array, and then the index value in square brackets, as follows:

/* we instantiate a new array, called "colors", and give it three values, "brown" (stored at index 0), "green" (stored at index 1), and "red" (stored at index 2) */
var colors = [ 'brown', 'green', 'red' ];

/* if we want to target the second item (i.e. "green") from our array, we can do so by calling its index, as follows */
console.log( colors[1] ); // this would print "green" to the console

In our case, since we're using a method that gets us an array of elements, and we want the second element in that array (i.e. the element stored at index 1), we would write our declaration as follows:

/* .getElementsByTagName() gets us an array to store in our lastName variable, but if we only want the second item (i.e. the item at index 1) to be stored instead of the whole array, we just need to specify the appropriate index at the end of the method call */
var lastName = document.getElementsByTagName( 'span' )[ 1 ];

Hope this helps to make it clearer!