Home > other >  How to make only the clicked element show the background color through javascript, and the rest of t
How to make only the clicked element show the background color through javascript, and the rest of t

Time:08-07

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>

CodePudding user response:

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>

  • Related