let div = document.querySelector('div')
fetch('https://opentdb.com/api.php?amount=5').then(response => {
return response.json()
}).then(data => {
div.innerHTML = `
${data.results[0].incorrect_answers.map(incorrect_answer => `<p class="answer">${incorrect_answer}</p>`).join("")}
`
div.addEventListener('click', function(event){
if (event.target.classList.contains('answer')) {
// all items to be black (remove selected/red class )
this.querySelector('.answer').classList.remove('selected')
// add the selected/red class to only the item clicked
event.target.classList.add('selected')
}
})
})
<div></div>
<style>
.answer{color:black;}
.selected{color:red;}
</style>
This loads options from a json file with fetch()
, when I click on one of the options it should highlight (color red), but all others should be black.
It only works with the first option, why the others don't change to black when other item is clicked?