Home > Blockchain >  Give a clicked li a background color
Give a clicked li a background color

Time:11-04

I want to give just the clicked li a background color. My script gives all the clicked a background color, but I just want the clicked one.

$('.tab').on("click", function() {
  $(this).css({
    backgroundColor: "#216180"
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<ul id="Nav">
  <li><a >aa</a></li>
  <li><a >bb</a></li>
  <li><a h >cc</a></li>
</ul>

CodePudding user response:

You did it correctly but you are not removing the background color from other elements which has been clicked before,

Since you have your a tags wrapped into li you should select the li element (parent) and then its siblings elements (other li's) and style its children which is the a tag

this change the background color of clicked element and remove the background color (transparent) from the other ones

$('.tab').on("click", function() {
  $(this).css({
    backgroundColor: "#216180"
  }).parent().siblings().children().css({
    backgroundColor: "transparent"
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<ul id="Nav">
  <li><a >aa</a></li>
  <li><a >bb</a></li>
  <li><a h >cc</a></li>
</ul>

  • Related