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 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

andren
andren
28,558 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,288 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!