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 JavaScript and the DOM (Retiring) Getting a Handle on the DOM Selecting by Id

Vic Mercier
Vic Mercier
3,276 Points


Why do we need to put [0] at the end ?Is it an obligation?

const myName = document.getElementsByTagName("h1")[0];
<!DOCTYPE html>
<script src = "js/app.js"></script>

2 Answers

Christopher Debove
Christopher Debove
Courses Plus Student 18,373 Points

Hi there! Depending on what you want.

Element.getElementsByTagName returns an HTMLCollection, not a single element. What you want in the challenge is to get a unique element, so adding "[0]" beside is getting the first element of this HTMLCollection.

Jennifer Nordell
Jennifer Nordell
Treehouse Teacher

Hi there! It doesn't seem like this question is about the challenge linked to this question. But you want to know if the the [0] is mandatory. No, not really. However, if it's not put there an array of all h1 tags will be returned and assigned to the myName variable. If this index.html had looked something like this:

<!DOCTYPE html>
<p>Paragraph one</p>
<h1>Address: </h1>
<p>123 Fake St.</p>
<h1>Telephone: </h1>
<script src = "js/app.js"></script>

... then an array containing every h1would be assigned to myName. But that wouldn't be correct, as your name is only stored in the first h1. That's what the [0] is for. It retrieves the very first h1 on the page and assigns it to myName.

Hope this helps! :sparkles: