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.

JavaScript JavaScript and the DOM (Retiring) Responding to User Interaction Listening for Events with addEventListener()

Aakash Srivastav
seal-mask
.a{fill-rule:evenodd;}techdegree
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,626 Points

Listening for Events with addEventListener()

What if I use for loop within each event handler just like-

listItems.addEventListener('mouseover', () => {
for(let i = 0 ; i< listItems.length ; i+=1){
listItems[i].textContent = listItems[i].textContent.toUpperCase();
}

listItems.addEventListener('mouseout', () => {
for(let i = 0 ; i< listItems.length ; i+=1){
listItems[i].textContent = listItems[i].textContent.toLowerCase();
}

Is it correct?If not why?

1 Answer

Steven Parker
Steven Parker
220,450 Points

This code doesn't show how "listItems" is established, but since it is being indexed and used in a loop, I assume that it represents an HTMLcollection. But a collection would not have a "addEventListener" method, only the individual elements would have that.

Also, it looks like the closing brace and parenthesis are missing from each function.

Aakash Srivastav
seal-mask
.a{fill-rule:evenodd;}techdegree
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,626 Points

But a collection would not have a "addEventListener" method, only the individual elements would have that.

I didn't know that . It clears all my doubt. Thanks Steven