Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
How to make only the clicked element show the background color through javascript, and the rest of the elements disappear?

How to make only the clicked element show the background color through javascript, and the rest of the elements disappear? Since I'm just learning the language, I don't quite know how to fix my code to achieve this effect?

thank you all.

function addStyle() {
  this.style.background = "blue";
}

var el = document.querySelectorAll('li');

for (var i = 0; i < el.length; i++) {
  el[i].addEventListener('click', addStyle);
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

As a corollary to David's answer you might also consider using event delegation. Instead of attaching multiple listeners to multiple elements add one to the containing element (the list) and catch events from its child elements as they "bubble up" the DOM. You can then check that the element is a list item, remove all the classes from the other list items, and set the class for the clicked child element.

const list = document.querySelector('ul');
const items = list.querySelectorAll('li');

list.addEventListener('click', handleClick);

function handleClick(e) {
  if (e.target.matches('li')) {
    items.forEach(item => item.classList.remove('blue'));
    e.target.classList.add('blue');
  }
}
.blue { background-color: lightblue; }
li:hover:not(.blue) { cursor: pointer; background-color: #efefef; }
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>

about 4 years ago · Juan Pablo Isaza Relatório

0

Before setting the background to blue, unset all of the backgrounds:

function addStyle() {
  // unset all backgrounds
  for (var i = 0; i < el.length; i++) {
    el[i].style.background = "unset";
  }
  // set this one to blue
  this.style.background = "blue";
}

var el = document.querySelectorAll('li');

for (var i = 0; i < el.length; i++) {
  el[i].addEventListener('click', addStyle);
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda