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

270
Vistas
Event.target.dataset returning undefined javascript

I am getting some issues while trying to get the data attribute of any html element.

The problem is i am getting the data attribute in 30% of the cases. The rest is returning undefined.

Here's what i want to trigger:

document.addEventListener("DOMContentLoaded",() => {
    document.body.addEventListener("click",(e) => {
        console.log("clicked");
        console.log(e.target.dataset.link + " is the link clicked") // this is returning undefined most of the times.
        if (e.target.dataset.link !== undefined) {
            console.log("got the link")
            navigateTo(e.target.dataset.link);
        }
    })

    // router();
})
<div class="cell" data-link="/dashboard/posts" tabindex="1">
    <i class="material-icons">assignment</i>
    <span>Posts</span>
 </div>

How is this even possible ?

And how can i prevent this ?

I can't remove the onclick event listener for the body.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

event.target is the element the event was targeted at, which may be inside your data-link element (like the i and span in your div). You can use the closest method with an attribute presence selector ([attribute-name]) to find the data-link element:

const dataElement = e.target.closest("[data-link]");

That checks e.target to see if it matches the CSS selector and, if it doesn't, looks to its parent to see if it matches, and so on until it reaches the document root. If it gets all the way to the root without finding it, it returns null.

Updated Snippet:

document.addEventListener("DOMContentLoaded",() => {
    document.body.addEventListener("click",(e) => {
        const dataElement = e.target.closest("[data-link]");
        if (!dataElement) {
            return; // There wasn't one
        }
        console.log(dataElement.dataset.link + " is the link clicked") // this is returning undefined most of the times.
        if (dataElement.dataset.link !== undefined) {
            console.log("got the link")
            // navigateTo(dataElement.dataset.link);
        }
    })

    // router();
})
<div class="cell" data-link="/dashboard/posts" tabindex="1">
    <i class="material-icons">assignment</i>
    <span>Posts</span>
 </div>


However, please note evolutionxbox's comment. You're recreating basic web functionality using non-semantic elements and JavaScript code. That destroys the accessibility of your page, and even for users who don't rely on assistive technology, it makes it impossible for them to use the advanced features of their browser to (say) open the link in a new tab, etc.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You attach the event listener to the document body. Is absolutely normal that you don't get the dataset: you can click out of the cell, or in a element into this.

You need attach the event to the desired elements with the data-link attribute:

document.addEventListener("DOMContentLoaded", () => {
  document.querySelectorAll('[data-link]').forEach(node => {
    node.addEventListener("click", (e) => {
        console.log("clicked");
        console.log(node.dataset.link + " is the link clicked")
    })
  })
})
<div class="cell" data-link="/dashboard/posts">
    <i class="material-icons">assignment</i>
    <span>Posts</span>
 </div>
 

<div class="cell">
    <i class="material-icons">assignment</i>
    <span>Posts</span>
 </div>
 

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