Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!