Skip to content
Advertisement

Change the background-color on a button after clicking

Hello i write on a rating button and i wanted to change the background color from the button after i clicked it but my code does nothing.

    <ul>
         <li><button class="btn"><p id="num">1</p></button></li>
         <li><button class="btn"><p id="num">2</p></button></li>
         <li><button class="btn"><p id="num">3</p></button></li>
         <li><button class="btn"><p id="num">4</p></button></li>
         <li><button class="btn"><p id="num">5</p></button></li>

       </ul>
          
-----


const btn = document.querySelector('.btn'); 

 btn.addEventListener('click', function onClick(){
    btn.style.backgroundColor = 'orange'; 
 });



Advertisement

Answer

const btn = document.querySelector('.btn'); is only targeting the first button.

You need to use querySelectorAll to select all buttons and add event listeners to each of them.

const allBtns = document.querySelectorAll('.btn'); 

allBtns.forEach(btn => {
   btn.addEventListener('click', function onClick(){
    btn.style.backgroundColor = 'orange'; 
 })
})
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement