Home > database >  How to get all attr value in same class by click() jQuery
How to get all attr value in same class by click() jQuery

Time:02-15

I am making a Simon game, but I need to get the "id" (attribute) value. but whenever I click on the different color it still gives me the first attr value which is in this case is green. how many times do I click on the red, blue, or yellow button but it still gives me a green value (the first one). help, please!

//Below code HTML

<div >
      <button  id="green"></button>
      <button  id="red"></button><br />
      <button  id="yellow"></button>
      <button  id="blue"></button>
    </div>

//Below code Jquery

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

CodePudding user response:

Reference to the button clicked. You do not necessarily need jQuery for this.

$(".btn").click(function () {
    var userChosenColor = $(this).attr("id");
    console.log('jQuery: '  userChosenColor);
});

/* non jQuery */
const btns = document.querySelectorAll('.btn');

btns.forEach(btn=> {
  btn.addEventListener('click', () => {
    console.log('JS only: ' btn.id)
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <button  id="green">1</button>
  <button  id="red">2</button><br />
  <button  id="yellow">3</button>
  <button  id="blue">4</button>
</div>

  • Related