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

Task 2

I'm stumped on task 2 for this challenge. I get the below error message when trying to use "getElementsByClassName".

"Try using the getElementsByTagName() method and using the second index (1)."

Question 1: I have no idea what they are talking about by "index (1)".

Question 2: Why wouldn't I be able to complete the task by setting var "lastName" = document.getElementsByClassName("last_name");?

app.js
var fullName = document.getElementById("full_name");
var lastName = document.getElementsByTagName("");
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

The getElementByTagName function is refering to the HTML tag, like the following:

 <a>  <p> <img>
```, etc.
 When you use this function, it selects all of the elements with that tag and places them in an array. That is why they mention the index. 

For example, if there are 4 <p> tags, and you want to select the 2nd of the <p> tags you would want to select the element in the array at index(1).

So, the following would load lastName with an array of all the span elements:
```var lastName = document.getElementsByTagName("span");```
Then the following would select the second span element, the one with the class of last_name:
```lastName(1);```

In practice, you could use the getElementsByClassName("last_name") to select the span with the last name. However, for this challenge they want you to use the getElementsByTagName() method.

Question 1: The getElementsByTagName() method returns an array of all the elements with the specified tag name. So index(1) refers to lastName[1]. Which is the second index in the returned array because the array starts at zero.

Question 2: Using the getElementsByClassName() method would give similar results but the task is to use the getElementsByTagName() method.