J
J
Java Script2020-05-04 11:06:04
JavaScript
Java Script, 2020-05-04 11:06:04

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

1 answer(s)
0
0xD34F, 2020-05-04
@E_Melqonyan

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 question

Ask a Question

731 491 924 answers to any question