Robin Leitner
Robin Leitner

Reputation: 47

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'; 
 });



Upvotes: 0

Views: 1320

Answers (3)

Amaan Rizvi
Amaan Rizvi

Reputation: 66

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'; 
 })
})

Upvotes: 2

Abbas Shaikh
Abbas Shaikh

Reputation: 324

Since you're selecting multiple buttons from DOM you've to querySelectorAll and then you need to loop over it to get your desired output

    const btn = document.querySelectorAll('.btn'); 
    btn.forEach(b => {
      b.addEventListener('click', function onClick(){
        b.style.backgroundColor = 'orange'; 
     });  
    })

Upvotes: 0

The KNVB
The KNVB

Reputation: 3844

You may try the following:

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

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

Upvotes: 0

Related Questions