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

Sathvik Reddy
Sathvik Reddy
6,223 Points

Challenge #4

Why does the below code not work? When I reference the console it shows that the 'ul' has been assigned a class name of 'list', but doesn't apply the CSS styling.

const ul = document.getElementsByTagName('ul');
ul.className = "list";

I am struggling a bit with understanding the different methods in accessing DOM elements.

Thanks!

1 Answer

Steven Parker
Steven Parker
229,785 Points

The "getElementsByTagName" function returns a collection, not a single element. And collections don't have a "className" property.

You could apply an index to "ul" to access a specific item in the collection.

Sathvik Reddy
Sathvik Reddy
6,223 Points

Then how was it able to assign the <ul> a class but not the CSS?

Steven Parker
Steven Parker
229,785 Points

JavaScript allows you to create new properties by simply assigning them. But giving a collection a "className" property won't do anything because the browser has no logic to make use of it. But using my index suggestion, you could assign the property on the list itself instead:

ul[0].className = "list";