'How can I implement the code in JavaScript so that whichever rating is selected, the background of that number will become highlighted in orange?

How can I implement the code in JavaScript so that whichever rating is selected, the background of that number will become highlighted in orange?

<ul class="rating-container">
    <li class="ratings"><button id="1" class="list-btn" type="button">1</button></li>
    <li class="ratings"><button id="2" class="list-btn" type="button">2</button></li>
    <li class="ratings"><button id="3" class="list-btn" type="button">3</button></li>
    <li class="ratings"><button id="4" class="list-btn" type="button">4</button></li>
    <li class="ratings"><button id="5" class="list-btn" type="button">5</button></li>
  </ul>

enter image description here



Solution 1:[1]

<ul class="rating-container">
    <li class="ratings"><button id="1" onclick="clickRating(1)" class="list-btn" type="button">1</button></li>
    <li class="ratings"><button id="2" onclick="clickRating(2)" class="list-btn" type="button">2</button></li>
    <li class="ratings"><button id="3" onclick="clickRating(3)" class="list-btn" type="button">3</button></li>
    <li class="ratings"><button id="4" onclick="clickRating(4)" class="list-btn" type="button">4</button></li>
    <li class="ratings"><button id="5" onclick="clickRating(5)" class="list-btn" type="button">5</button></li>
  </ul>

<script>
   function clickRating(rating) {
      for (let i = 1; i<=5; i++) {
         if (i<=rating) {
             document.getElementById(i).style.backgroundColor = 'yellow'
         } else {
            document.getElementById(i).style.backgroundColor = 'unset'
         }
      }
   }
</script>

Solution 2:[2]

If you're using native JavaScript, attach an event listener to the container holding the buttons and listen for click events. When a button is clicked, add a class, and with that class, you can style the button to be whatever you want.

const ratingContainer = document.getElementById("rating")
let prevTarget = null
ratingContainer.addEventListener("click", (e) =>{
   const target = e.target.closest("button")
   //ensure not the same button
   if(target !== prevTarget) {
      target.classList.add("highlight")
      if(prevTarget) prevTarget.classList.remove("highlight")
      prevTarget = target
   }
})
.highlight{
  background-color: orange;
}
<div id="rating">
<button id="1">button1</button>
<button id= "2">button2</button>
<button id= "3">button3</button>
<button id= "4">button4</button>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Prana
Solution 2