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 Perform: Selecting Elements

Why use document.getElementByTagName("span")[1] instead of document.getElementsByClassName("last_name")?

In the selecting elements code challenge, the correct answer is document.getElementByTagName("span")[1]. Why we use it instead of document.getElementsByClassName("last_name")?

Cale Matteson
Cale Matteson
11,303 Points

Actually by looking at what you pasted into the question, it doesn't pass because "document.getElementByTagName("span")[1]" isn't right. its "Elements" not "Element" it was simply a spelling error! It plagued me for about 10 minutes too! ID's are unique, and therefor only return an "Element". but Tag Name returns a whole array of "Elements" if that helps you remember at all.

However, the answer Robert gave is true as well. But notice the class selector is spelled "Elements" as well. Because classes are not unique it returns as array as well.

2 Answers

Hi Chuong,

You can use either way - I tested it. When selecting by class name, you'll get an array of elements just like when selecting by tag name.

// by tag name
var lastName = document.getElementsByTagName("span")[1];

// by class name
var lastName = document.getElementsByClassName("last_name")[0];

Thanks, i didn't include the array, that's why it did not pass the challenge