Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQueryEventObject & target

Tags:

typescript

In an event handler I need to determine the DOM Element which got clicked. I would expect to use jqEvent.target.attributes['tag'] where jqEvent is of type JQueryEventObject. But 'target' is defined in lib.d.ts as of type EventTarget which contains nothing I can use...

Have I missed something?

like image 423
andyks Avatar asked Dec 30 '25 18:12

andyks


2 Answers

I use this and it works fine...

    private funct(event: JQueryEventObject) {
        var state = $(event.target).prop('checked');
    }
like image 62
Matěj Pokorný Avatar answered Jan 02 '26 12:01

Matěj Pokorný


Here is the definition of EventTarget (found in dom.generated.d.ts, distributed with TypeScript):

interface EventTarget {
    removeEventListener(type: string, listener: EventListener, useCapture?: boolean): void;
    addEventListener(type: string, listener: EventListener, useCapture?: boolean): void;
    dispatchEvent(evt: Event): boolean;
}

There could be other classes that implement EventTarget in order to attach events, so the safest API definition is to set Event.target to the object that implements EventTarget where the listeners are attached.

In the jQuery context, Event.target will almost certainly be of type HTMLElement (not type JQuery as in Andree's answer). For your example of jqEvent.target.attributes['tag'], the correct way is to notify the compiler that it is actually a Node (grandparent interface of HTMLElement), which does have the attributes property:

(<Node> jqEvent.target).attributes['tag']

The above cast could also be to HTMLElement if you are explicitly accessing properties of the more specific interface. Using the most general interface possible is considered object-oriented best practice.

like image 32
wmorrell Avatar answered Jan 02 '26 10:01

wmorrell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!