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 can't we just use getElementsByClassName, instead of getElementsByTagName?

I went on to the challenge just after this video, and don't understand why I can't use get ElementsByClassName to select and assign the second <span> with the class .last_name.

Why bother dealing with getElementsByTagName which requires you to deal with index numbers and such? Or is it simply because getElementsByTagName is used in the video, and you're supposed to copy it 'because'?

Thank you!

2 Answers

28,507 Points

You can in fact use getElementsByClassName to solve this challenge.

But one thing you seem to have misunderstood is that both the getElementsByTagName and getElementsByClassName methods requires you to use indexes to access elements.

Both of those methods returns a list of elements, even if there is only one element matching the tag / class you specified. The getElementById and querySelector methods are the only DOM selection methods that only return a single element, and therefore does not need to have an index used.

Here is a solution to this task that uses the getElementsByClassName method:

var fullName = document.getElementById("full_name");
var lastName = document.getElementsByClassName("last_name")[0];
Jesus Mendoza
Jesus Mendoza
23,274 Points

Hey speir,

I guess it's because the teacher wants you to practice and get familiar with the getElementsByTagName method.

With classes you also need to add the index of the element you want to select though!