I'm trying to change the background color of dynamic html elements (span
) 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>');
};
$(".questionBox").on("click", "span.pilihan", function() {
Array.from(document.getElementsByClassName("pilihan"))
.forEach((element) => element.style.backgroundColor = "red");
});
However, I want only the one clicked that changes color, not all span.pilihan
, but my code above change the color off all to be red.
Any idea?
Write this:
$(".questionBox").on("click", ".pilihan", function() {
$(this).css("background", "red");
});