Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


1 Answer

Jennifer Nordell
Jennifer Nordell
Treehouse Teacher

Hi there, Sean Flood!

The answer lies in what is returned by getElementsByTagName. That returns an HTMLCollection which is much like an array that contains DOM elements. In this case, it's picking all <ul> tags. Even though there may only be a single <ul> on that page, the result is still in an array-like form. So instead of getting back the ul, you're getting back a collection of <ul>s.

As an example, on this page I opened up the console and did this in the console:

let result = document.getElementsByTagName('ul');

Then I logged out the value of result which was:

[ul.header-nav-list.header-nav-item-profile-points-size-6, ul, ul.notification-list, ul#forum-post-actions,...

It's actually so long that it's truncated in the console :smiley:

But even if it had been a single <ul> with the class "my-awesome-list" then the result would be:


So if we wanted to set an event listener on that, we'd have to pick document.getElementsByTagName('ul')[0];. Attempting to attach an event listener to a group of elements will result in an error because addEventListener is not a valid method on an HTMLCollection.

Also, note the "s" in the name that makes it plural: getElementsByTagName as opposed to getElementById. The first is plural because it will always return a group even if the group happens to only have a single member. The second is singular because an ID must be unique on the page so there can only ever be one with that id (assuming it's valid HTML). This is why when you pick by ID you get back a single element as opposed to a group of them.

Hope this helps! :sparkles: