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

123
Visualizações
Attribute selector does not take into account the elements contained in it

I have a line of HTML code:

<a href="/posts" class="nav__link" data-link><i class="fa fa-file"></i><span>Pages</span></a>

and then I catch the event, cancel the transition by the link using my handler:

document.body.addEventListener("click", e => {
        if (e.target.matches("[data-link]")) {
            e.preventDefault();
            navigateTo(e.target.href);
        }
    });

As long as there is only text in the a tag, everything is fine, but as soon as nested span, i, and so on tags appear in it, this code does not work when you click on them.

How can I change this JS code so that it also applies to nested elements?

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

0

You might use .closest method:

document.body.addEventListener("click", e => {
  if (e.target.closest('a').matches("[data-link]")) {
    e.preventDefault();
    navigateTo(e.target.href);
  }
});

function navigateTo() {
  console.log("let's go!")
}
a,
a i,
a span {
  display: inline-block;
  padding: .5em;
  border: solid 1px
}
<a href="/posts" class="nav__link" data-link><i class="fa fa-file">Nested element</i> <span>Another Nested element</span> Link tag itself</a>

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