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

129
Vistas
How to change the color only the clicked element of many iterated dynamic elements

I'm trying to change the background color of dynamic html elements (span) to be red when user clicks them.

function showQuestion(){
    for(let i = 0; i < QuesPartA.length; i++){
      $(".questionBox").append('<div class="Question">Number '+ parseInt(i+1) +'</div>');
      QuesPartA[i]['option'].forEach(option => {
          $(".questionBox").append('<span class="pilihan">'+option +' </span><br>');  
      });
  } 

$(".secondBox").append('<a href="Listening Part A.html" class="btnToPartB">Continue to Part B</a>');
  };

But I want only the one clicked that changes color, not all span.pilihan. I have tried some ways, but it ended up either changing all spans to be red or not changing at all. Any ideas how to do it effectively?

Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use jQuery events to get the element of click.
Like below:

$(() => {
 generateQuestion(1);
});

var q = 1;

function generateQuestion(num) {
  var question = document.createElement("span");
  question.innerHTML = "Question " + num;
  document.body.append(question);
}

$("body").on("click", "span", function(){
  $(this).css("background", "red");
  q++;
  generateQuestion(q);
});
span {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Edit: now delegate

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