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

Joseph Acevedo
Joseph Acevedo
10,800 Points

Why doesn't this work for part 2? var lastName = document.getElementsByClassName('last_name');

I know that using the second element of the 'span' array works. But why does the above code cause a conflict with task 1?

app.js
var fullName = document.getElementById('full_name');
var lastName;
index.html
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1 id="full_name"><span class="first_name">Andrew</span> <span class="last_name">Chalkley</span></h1>

<script src="app.js"></script>
</body>
</html>

2 Answers

Merritt Lawrenson
Merritt Lawrenson
13,477 Points

'document.getElementsByClassName()' returns an array, unlike 'document.getElementById()', which returns the element itself. This is because an ID can only belong to one HTML element, while classes can and often do have multiple elements that belong to that class. 'document.getElementsByClassName()' returns an array with all the elements in the class, even if it's just one element.

This challenge wants you to use the method 'getElementsByTagName()', which does the same but by tag name, in this case 'span'. To select the second 'span' tag on the page:

var fullName = document.getElementById('full_name');
var lastName = document.getElementsByTagName('span')[1];

Remember that you need the index there to specify which element you mean. In this case, you mean the second 'span'.

Joseph Acevedo
Joseph Acevedo
10,800 Points

That makes so much sense! Thanks!!!

Merritt Lawrenson
Merritt Lawrenson
13,477 Points

No problem! Please select my answer as 'best answer' if you found it most helpful, I'd appreciate it!

Damien Watson
Damien Watson
27,419 Points

Hi Joseph, Get 'elements' by class name returns an array of elements by that classname (even if its an array of 1). Because of this, you need to get the first element (being '0'). Try:

var lastname = document.getElementsByClassName('last_name')[0];