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

Only the first li responds during mouseover and mouseout. The newly created <li> elements do not respond. Please help!

This is my Javascript File:

const addGameInput = document.querySelector('input.addGameInput'); const addGameButton = document.querySelector('button.addGameButton'); const deleteGameButton = document.querySelector('button.deleteGameButton'); const listItems = document.getElementsByTagName('li');

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

listItems[i].addEventListener('mouseout', () => { listItems[i].textContent = listItems[i].textContent.toLowerCase(); }); }

addGameButton.addEventListener('click', () => { let ul = document.querySelector('ul') let li = document.createElement('li') li.textContent = addGameInput.value; ul.appendChild(li); addGameInput.value = ''; });

deleteGameButton.addEventListener('click', () => { let ul = document.querySelector('ul') let li = document.querySelector('li:last-child') ul.removeChild(li);
});

This is my HTML file:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home</title> <link rel='stylesheet' href='style.css'> </head> <body> <h1>Games</h1> <h2>Gameslist</h2> <ul> <li>One</li> </ul> <input type='text' class='addGameInput'> <button type='text' class='addGameButton'>Add</button> <button type='text' class='deleteGameButton'>Delete</button> <script src="script.js"></script> </body> </html>

1 Answer

Zaid Khan
Zaid Khan
12,746 Points

Hi xajx In order to see the effect on every li. You can target the direct global element of li which is ul. And add the event to let the listener know which particular li to target.

Like this:

let ul = document.querySelector('ul');

ul.addEventListener('mouseover', (e) => { 
      if(e.target.tagName === 'LI'){
             e.target.textContent = e.target.textContent.toUpperCase();
      }
});

ul.addEventListener('mouseout', (e) => { 
      if(e.target.tagName === 'LI'){
            e.target.textContent = e.target.textContent.toLowerCase(); 
      }
}); 

Also, it's a good practice to wrap your code in 3 backticks. Like the way I did it. Otherwise, it's tough to understand the code.