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

268
Visualizações
EventListener added to parent div, but event.target becomes children element if clicked on

I'm working with card shaped divs that I need to be clickable. I'm using JS (stimulusJS) to add an EventListener to them so when the user clicks on the card, the event listener is fired adding some CSS classes and populating some hidden fields with data that comes from the divs dataSet.

card

<div class="card d-flex flex-column data-selectable-target="selectable" data-pricing-model-value="flat_fee">
   <div class="self-end">
      <strong>
        <span class="mr-3" data-toggle="tooltip" title="<%= t(".tooltip") %>"><%= icon("exclamation-circle", classes: "h-4 w-4") %></span>
      </strong>
   </div>
   <h5><%= t(".title") %></h5>
   <p> <%= t(".description") %></p>
</div>

JS controller

import { Controller } from 'stimulus';

export default class extends Controller {
  static targets = ["selectable"]

  connect() {
    this.selectableTargets.forEach((element) => {
      element.addEventListener("click", (event) => {
        this.select(event.target);
      });
    })
  }

  select(element) {
    element.classList.add("selected")
    this.selectableTargets.forEach((target) => {
      if (target != element) {
        target.classList.remove("pricing-model-selected")
      }
    })
  }
}

Problem: I'm using event.target expecting to get the parent div to which I added the EventListener. Instead, if I click on the card's h5 or p elements, they become the event.target messing up my implementation. Is there anything that could be done to ensure that event.target always refers to the parent div to which the EventListener was added?

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