Home > Back-end >  javascript - get element that was clicked from collection of items
javascript - get element that was clicked from collection of items

Time:07-07

Having this code:

let ev = document.querySelectorAll('.event p')

for (let i = 0; i < ev.length; i  ) {
    ev[i].addEventListener("click", function (e) {
        // add this only for current clicked elem
        e.currentTarget.src = './icon.png';
        // And the rest of items should have this:
        ev[i].src = './warning.png';
    });
}

How can i change warning.png to all elements in this loop, but change src for element to have icon.png that was clicked? So kind of toggle. My code is not working as expected. Thanks.

CodePudding user response:

In your code after the click event on element, that element's src is changing but later on it is changing again to ./warning.png. Rearranging them will solve the problem.

let ev = document.querySelectorAll('.event p');
const evLen = ev.length;
for (let i = 0; i < evLen; i  ) {
    ev[i].addEventListener("click", function (e) {
       ev[i].src = './warning.png'; 
       this.src = './icon.png';
    });
}

CodePudding user response:

You can reuse ev inside the event listener, like this: ev.forEach(evt => evt.src = './warning.png');

If the list of .event p changes, recalculate the list again, e.g. put ev = document.querySelectorAll('.event p') inside the listener.

let ev = document.querySelectorAll('.event p')

for (let i = 0; i < ev.length; i  ) {
    ev[i].addEventListener("click", function (e) {
        // add this only for current clicked elem
        e.currentTarget.src = './icon.png';
        // And the rest of items should have this:
        ev.forEach(evt => evt.src = './warning.png');
    });
}
  • Related