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 w/JavaScript - Selecting Elements

Hi, I'm having a hard time with the first code challenge in section two, problem #2. This is my code and the first problem is passing, but the second is not. The instructions are to:Select the second SPAN element on the page and assign it to the variable lastName on line 2. Take a look in the index.html to see the structure of the document. Can anyone help please?

var fullName =  document.getElementById("full_name");
var lastName =  document.getElementById("last_name");

10 Answers

They wanted you to grab the tag name (in this case, SPAN) instead of by Id as in the first task.

var lastName = document.getElementsByTagName("span")[1];

Since there were two span tags, the 1 selects the appropriate tag.

Thank you, it worked.

I had getElementById and getElementByTagName.

The second part is supposed to be plural.

getElementsByTagName;

You are correct sir.

I think I see what you're saying. I'm pretty sure you can use the ElementById() if you're provided an ID, but the task asked to select the tag name. I think the reason is because if you select both elements by ID it might be redundant. There would have to be two ID's, one for the first name and one for the last. If you select the tag, the "span", then you get the entire full name.

I'd like to practice more with this outside of the workspace and see the results.

This one had me stumped too. Now I realize how valuable it is to copy and paste from MDN as Andrew did in the video. I had "getElementByID" rather than "getElementById". I was doing it right but had an uppercase "D".

var fullName = document.getElementById("full_name");
var lastName = document.getElementByClassName("last_name");

I tried this ^ and it didn't work. But I can't figure out why. Maybe it's time to take a break?

In your first line it's document.getElementByID - both I and D are caps. :)

var fullName = document.getElementById("full_name");

var lastName = document.getElementsByTagName("span")[1];

That was a tricky one thanks for the help!

var fullName = document.getElementById("full_name");

var lastName = document.getElementsByTagName("span")[1];

var fullName = document.getElementById("full_name");

var lastName = document.getElementsByTagName("span")[1];

why could you not use getElementById(); considering you are provided an ID ?