Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 142075

How to highlight the clicked item from JS fetch()

$
0
0
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?


Viewing all articles
Browse latest Browse all 142075

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>