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

Stephen Gough Jr
Stephen Gough Jr
4,187 Points

Can't get <li> elements to be capitalized with JS

I wanted to get a little practice and boost my confidence by doing something I thought was simple, but even this simple exercise has proved too much, and I'm beginning to wonder if I am wasting my time. I'm using notepad++ for this exercise, and the JS file is properly scripted inside the HTML. My JS code is:

var nameProper = document.getElementsByTagName("li"); nameProper.addEventListener("mouseover", (event) => { if (event.target.tagName = "li") { event.target.toUpperCase() }; });

Whenever I run it, I get some type error on line 2 (saying name.Proper isn't a function) and it won't even run. I tried copying a bit of code I've used in the TeamTreeHouse videos (I'm currently on the "Javascript and the DOM" course of the Front End Development Track). What am I doing wrong? How can I get a much stronger grasp on JS? As I am now, I feel like I understand what I'm being taught, but trying to apply anything I've learned is amazingly inefficient.

1 Answer

Steven Parker
Steven Parker
231,007 Points

the "getElementsByTagName" function returns a collection of elements. But wile a single element has a "addEventListener" function, a collection does not.

If you want to add an event listener to each item in the collection, you'll need a loop to set them one at a time. Or if you only want to add it to a single one, you need to pick it out of the collection with an index.