Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda