Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

138
Vistas
How to get all attr value in same class by click() jQuery

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 class="container">
      <button class="btn green" id="green"></button>
      <button class="btn red" id="red"></button><br />
      <button class="btn yellow" id="yellow"></button>
      <button class="btn blue" id="blue"></button>
    </div>

//Below code Jquery

$(".btn").click(function () {
    var userChosenColor =$(".btn").attr("id");
    console.log(userChosenColor);
});
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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 class="container">
  <button class="btn green" id="green">1</button>
  <button class="btn red" id="red">2</button><br />
  <button class="btn yellow" id="yellow">3</button>
  <button class="btn blue" id="blue">4</button>
</div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda