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 ><p id="num">1</p></button></li>
<li><button ><p id="num">2</p></button></li>
<li><button ><p id="num">3</p></button></li>
<li><button ><p id="num">4</p></button></li>
<li><button ><p id="num">5</p></button></li>
</ul>
-----
const btn = document.querySelector('.btn');
btn.addEventListener('click', function onClick(){
btn.style.backgroundColor = 'orange';
});
CodePudding user response:
You may try the following:
const btnList = document.querySelectorAll('.btn');
btnList.forEach(btn => {
btn.addEventListener('click', function onClick() {
btn.style.backgroundColor = 'orange';
});
})
CodePudding user response:
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';
});
})
CodePudding user response:
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';
})
})