Why in this case:
var ele = <HTMLDivElement>document.getElementById("toolbar"); ele.addEventListener("click", function (e) { if (e.target.tagName === "SPAN") { console.log(e.target.tagName) } }, false);
Visual Studio shows me this error?
Build: Operator '===' cannot be applied to types 'HTMLElement' and 'string'.
Property 'tagName' does not exist on type 'EventTarget'.
When I run a script works fine.
How to write it properly?
Thank you.
target as HTMLElement; if (element. tagName === "SPAN") { console. log(element. tagName) } }, false);
addEventListener('input', function (event) { const target = event. target as HTMLElement; console. log(target.id); }); This is necessary, because the EventTarget interface contains only a few properties like addEventListener , removeEventListener and dispatchEvent .
The error "Property 'value' does not exist on type 'EventTarget'" occurs when we try to access the value property on an element that has a type of EventTarget . To solve the error, use a type assertion to type the element correctly before accessing the property. This is the index.
js error "Property 'value' does not exist on type EventTarget" occurs when the type of the event parameter is incorrect. To solve the error, type the event as React. ChangeEvent<HTMLInputElement> . You can then access the value as event.
I would adjust that code snippet like this:
var ele = <HTMLDivElement>document.getElementById("toolbar"); ele.addEventListener("click", (ev: MouseEvent) => { var element = ev.target as HTMLElement; if (element.tagName === "SPAN") { console.log(element.tagName) } }, false);
Casting the event property target
to HTMLElement
will give us all the proper properties of the underlying element.
Check it in the playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With