-1

I'm looping through the properties of an HTMLElement and doing some things with the element's event names. Do HTMLElement event properties always begin with "on"? My approach is working fine at the moment, but I would like to know if it is reliable:

for (let key in elem) {
    // check if hasOwnProperty is false to make sure the property isn't spoofed
    if (!elem.hasOwnProperty(key) && key.indexOf("on") === 0) {
        const eventName = key.substring(2);
        // do stuff here with eventName
    }
}

Note: The only event name I can think of that doesn't follow the convention is DOMContentLoaded, but it's an event on the Document object, not HTMLElement.

user3163495
  • 2,425
  • 2
  • 26
  • 43
  • 2
    In fact, don't use those. In any way. They're the legacy single-binding event handler from _waaay_ back in the DOM1 days. The event listener mechanism has been `addEventListener` for decades now, introduced back in the year 2000 when DOM2 replaced the original "we're still figuring this stuff out" DOM spec, shortly after HTML 4.01 became the standard. – Mike 'Pomax' Kamermans Aug 05 '23 at 20:26
  • @Mike'Pomax'Kamermans The single-binding event handler is not "legacy". It is just one of two options to bind an event. Option #2 is with `addEventListener`. The `addEventListener` method has not replaced the single-binding event handler. They both exist as tools for developers and are neither has been deemed "legacy" or otherwise deprecated. As JavaScript evolves and HTML elements gain new events, the event is made bindable in both the event handler property AND via `addEventListener`. – user3163495 Aug 05 '23 at 20:51
  • I didn't replace it, because JS made the decision to never remove features. But it _is_ legacy (it's just not _deprecated_ because JS never deprecates anything), and the (not even) modern pattern is to register event listeners. – Mike 'Pomax' Kamermans Aug 05 '23 at 21:54

0 Answers0