-1

I have 3 buttons with same class(myBtn), I want to change the background color of the button I clicked using querySelectorAll and addEventListener.

I'm making a bigger project this is just an example of my problem, I'm into pure javascript and i don't wanna use onClick method in my html for some reason.

var a = document.querySelectorAll('myBtn')[2];
a.addEventListener("click", callFunc());
function callFunc() {
  this.style.backgroundColor = "red";
}
<p>Click the button to change its background color.</p>

<button id="myBtn">uno</button>
<button id="myBtn">dos</button>
<button id="myBtn">tres</button>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • `id` on html element must be unique per document. `queryselectorall` return an array you need to iterate it and add the event listener. – Rafael Herscovici Oct 14 '19 at 08:18
  • 1. Change to class and not id, 2 you need a dot 3. You need to remove the () from the event handler assignment : `var a = document.querySelectorAll('.myBtn')[2]; a.addEventListener("click", callFunc); function callFunc() { this.style.backgroundColor = "red"; }` – mplungjan Oct 14 '19 at 08:37

1 Answers1

1
  • ID should be unique. Use classes.
  • Create a class (i.e: .red) in your stylesheet and use .classList.toggle() or .classList.add()
  • querySelectorAll() returns a NodeList collection of Elements. Use a .forEach()
  • PS: [2] will give you only one element, not "... of the one I clicked"

const myBtn = document.querySelectorAll('.myBtn');
const changeBackground = ev => ev.currentTarget.classList.toggle('red'); 

myBtn.forEach(el => el.addEventListener('click', changeBackground));  
.red { background: #f00; }
<button class="myBtn">uno</button>
<button class="myBtn">dos</button>
<button class="myBtn">tres</button>
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313