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 trialChuong Nguyen
8,256 PointsWhy 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")?
2 Answers
Robert Richey
Courses Plus Student 16,352 PointsHi 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];
Chuong Nguyen
8,256 PointsThanks, i didn't include the array, that's why it did not pass the challenge
Cale Matteson
11,303 PointsCale Matteson
11,303 PointsActually 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.