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.
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.