Help with highlighting a singular list element on click.

Click target is highlighted, while other elements, if they were ones being highlighted beforehand, lose it. JS in this example is what I was suggested to do here some time ago: https://codepen.io/DovahTheKiin/pen/WNmQOqM Problem with this method is that if you click on any child element, it does not apply the class on the parent element. This link was suggested to me multiple times here as well, but it suffers from the same problem: https://gomakethings.com/listening-for-events-on-multiple-elements-using-javascript-event-delegation/
if (event.target.matches('.click-me')) {
// Do something...
}
if (event.target.matches('.click-me')) {
// Do something...
}
If you click on any child element of the "matches" element, event is not working.
Listening for events on multiple elements using JavaScript event de...
In JavaScript, event listeners have to be attached to individual elements. You can’t attach them to an array or node list of matching elements like you might in jQuery. Today, we’re going to look at a technique that you can use listen for the same even on multiple elements without having to attach to each element individually: event delegation. ...
3 Replies
clevermissfox
clevermissfox11mo ago
try event.target.closest(“.parent”)
MarkBoots
MarkBoots11mo ago
this should work for you
const randomDiv = document.querySelector(".random-div");
randomDiv.addEventListener("click", clickHandler);

function clickHandler(e){
const clickDiv = e.target.closest(".click-div");
const currentActive = e.currentTarget.querySelector(".active");
if(currentActive) currentActive.classList.remove("active");
clickDiv.classList.add("active");
}
const randomDiv = document.querySelector(".random-div");
randomDiv.addEventListener("click", clickHandler);

function clickHandler(e){
const clickDiv = e.target.closest(".click-div");
const currentActive = e.currentTarget.querySelector(".active");
if(currentActive) currentActive.classList.remove("active");
clickDiv.classList.add("active");
}
Dovah
DovahOP11mo ago
Works! Thanks!
Want results from more Discord servers?
Add your server