Answer the question
In order to leave comments, you need to log in
How to write it with one loop?
const elem = document.querySelectorAll('.box');
for (let i = 0; i < elem.length; i++) {
elem[i].addEventListener('click', function () {
for (let x = 0; x < elem.length; x++) {
elem[x].style.background = 'black';
}
elem[i].style.background = 'red';
})
}
Answer the question
In order to leave comments, you need to log in
Instead of assigning individual handlers to each element, make one delegate:
document.addEventListener('click', ({ target: t }) => {
if (t.classList.contains('box')) {
for (const n of document.querySelectorAll('.box')) {
n.style.background = n === t ? 'red' : 'black';
}
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question