0

i learned in the past to do this with jQuery but now i want to make it in pure vanilla js so this use to be my code with jQuery

$(".btn").click(function () {
  var userChosenColor = $(this).attr("id");
});

and this is what i'm doing with pure js

var bTn = document.getElementsByClassName("btn");
for (var i = 0; i < bTn.length; i++) {
  bTn[i].addEventListener("click", (e) => {
    var userChosenColor = bTn[];
    console.log(userChosenColor);
  });
}
Phil
  • 157,677
  • 23
  • 242
  • 245
Alan
  • 349
  • 3
  • 15

1 Answers1

2

that ?

document.querySelectorAll('.btn')
          .forEach(bt=>{
            bt.onclick=()=>{
              console.clear()
              console.log( bt.id )
          } } )
<button id="bt_1" class="btn">bt 1 </button>
<button id="bt_2" class="btn">bt 2 </button>
<button id="bt_3" class="btn">bt 3 </button>
<button id="bt_4" class="btn">bt 4 </button>

Or, to consider Phil's remark:

document.querySelectorAll('.btn')
          .forEach(bt=>{
            bt.addEventListener('click',function() {
              console.clear()
              console.log( bt.id )
          }) })
<button id="bt_1" class="btn">bt 1 </button>
<button id="bt_2" class="btn">bt 2 </button>
<button id="bt_3" class="btn">bt 3 </button>
<button id="bt_4" class="btn">bt 4 </button>
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
  • Why would you choose `onclick` over `addEventListener`? What if OP's buttons already have an `onclick` assigned? This is certainly not the jQuery equivalent. Other than that though, it's pretty good – Phil Sep 07 '20 at 02:54
  • @Phil all the same, it is very rare that the action of a button requires the use of several event recipients. – Mister Jojo Sep 07 '20 at 02:57
  • Doesn't matter. The only thing OP needs to change in the code in their question is to use `e.target.id` which is included in the answers in the duplicate – Phil Sep 07 '20 at 03:18
  • I mean, just like the bit of text above that link says... _"This question already has answers here"_. A duplicate vote doesn't necessarily mean the questions are the same – Phil Sep 07 '20 at 03:25
  • I've added another duplicate just to make it clear. Your solution works as well of course – Phil Sep 07 '20 at 03:31
  • @thanks, by the way I added to my answer the addEventListener method – Mister Jojo Sep 07 '20 at 03:34