Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: How to check tagName in eventTarget?

Tags:

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.

like image 943
Klick Avatar asked Nov 21 '15 18:11

Klick


People also ask

How do I get tagName from event target?

target as HTMLElement; if (element. tagName === "SPAN") { console. log(element. tagName) } }, false);

How do I find the events target ID in typescript?

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 .

Does not exist on EventTarget?

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.

Does not exist on type EventTarget react?

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.


1 Answers

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

like image 168
Radim Köhler Avatar answered Oct 16 '22 13:10

Radim Köhler