Issue
How do I make TypeScript happy regarding this error:
Property 'dataset' does not exist on type 'EventTarget'
I get it when I try to implement this code snippet:
document.addEventListener(
"click",
(event) => {
event.preventDefault();
if (event !== null && event.target !== null) {
const element = event.target as Element;
if (element.matches(".dropdown-item.city")) {
const cityName = event.target.dataset.value;
console.log("City =", cityName);
dropdown.classList.toggle("active");
}
}
},
false
);
Solution
One option rather than asserting the type is to check that the element is the right type in your conditional. In this case, I believe you want to make sure it's an instanceof HTMLElement
.
document.addEventListener(
"click",
(event) => {
event.preventDefault();
if (event !== null && event.target instanceof HTMLElement) {
const element = event.target;
if (element.matches(".dropdown-item.city")) {
const cityName = element.dataset.value;
console.log("City =", cityName);
dropdown.classList.toggle("active");
}
}
},
false
);
Answered By - Nick
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.