Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

391
Visualizações
Onclick, Highlight only one list item in an Unordered list

I am following a code to make a quiz. I am building a function to highlight one list item and add a class to it.

function chooseAnswer(){
    answer.querySelectorAll('li').forEach((option)=> { 
    option.addEventListener('click',()=>{
        if(answer.querySelector('.selected')){
            let activeAnswer=answer.querySelector('.selected');
            activeAnswer.classList.remove('selected') 
        }else
        option.classList.add('selected')
})

The code is working but i do not understand the if condition from the source. Can someone help?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

if(answer.querySelector('.selected')) statement is used to check whether there are any elements of answer, which have the .selected class

about 4 years ago · Juan Pablo Isaza Relatório

0

answer.querySelector('.selected') will return the element with .selected class if it exists within the answer element.

If there is no .selected class within the answer element, it will return null.

In this code:

if(answer.querySelector('.selected')){
            ---
   }else
        option.classList.add('selected')

If the if condition is null that means there was no .selected element found. So the else block gets executed and it adds a .selected class to option.

But if there was a .selected class inside the answer element, the if condition would be truthy and would execute. Removing the .selected class.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda