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

O V
O V
2,483 Points

Why do you need to assign listItems.textContent to itself?

In this example:

listItems.addEventListener('mouseover', () => { listItems.textContent = listItems.textContent.toUpperCase(); }); Why do we have to assign listItems.textContent.toUpperCase(); to listItems.textContent? I know it doesn't work if we don't but I want to understand WHY is it that i cannot just the following instead:

listItems.addEventListener('mouseover', () => { listItems.textContent.toUpperCase(); });

2 Answers

Ryan Groom
Ryan Groom
17,181 Points

O V The reasoning behind this is sort of in your question. When you call listItems[0].textContent.toUpperCase(); you are grabbing a value (which in this instance is the uppercase version of the text content inside of the first instance of your list items) but you are not actually setting(or assigning) that value to anything. Putting listItems[0].textContent on the left side of the operator actually sets(assigns) that uppercase value to the text content of the first instance of a list item. To attempt to simplify this explanation, imagine you want to set the text content to the word "hello". You couldn't just put

listItems[0].addEventListener('mouseover', () => { "hello" });

instead you would have to put:

listItems[0].addEventListener('mouseover', () => { listItems[0].textContent = "hello"; });

I hope this helps!

KRIS NIKOLAISEN
KRIS NIKOLAISEN
54,370 Points

From MDN

The toUpperCase() method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable.