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

144
Visualizações
Unable to capture the closest span element on mouse click

The MDN specification of the closest method reads that the method traverses the DOM upwards, in the direction to the document root. But what method does one need to use in my case instead of closest then?

In my HTML page I have the following code:

<div class="slider__steps">
  <span></span>
  <span></span>
  <span class="slider__step-active"></span>
  <span></span>
  <span></span>
</div>

In my JS file I want to capture the closest span element to a mouse click and change its CSS class. I try to do this as follows:

moveSlider(elem) {
    let sliderSteps = elem.querySelector('.slider__steps');
    let spans = sliderSteps.querySelectorAll('span');
    elem.addEventListener('click', moveThumb);
    function moveThumb(event) {
      for (let span of spans) {
        span.classList.remove('slider__step-active');
      }
      event.target.closest('span').classList.add('slider__step-active');
    }
  }

But the error I get is

Uncaught TypeError: event.target.closest(...) is null

How does one actually catch these spans on mouse clicks?

about 4 years ago · Juan Pablo Isaza
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