Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

HTMLElement.onerror — handling the error event

HTMLElement.onerror assigns a handler for an element's error event, such as an image loading failure. It is not a global mechanism for catching JavaScript exceptions.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

element.onerror = function (event) { /* handle error */ };
element.onerror = null;

HTMLElement.onerror is the event-handler property for error. On an ordinary element, its function receives one event object, not the five arguments associated with global error handling.

Assigning a function replaces the property's previous value; assigning null removes that handler. To register independent functions, use addEventListener('error', handler).

Do not confuse this property with window.onerror: when reporting an exception, the global handler receives message, source, lineno, colno, error, and returning true cancels the event. On an ordinary element, returning false cancels the event only if it is cancelable. The onerror properties of body and frameset have special forwarding behavior targeting Window.

The example dispatches a synthetic event without fetching resources. It checks handler invocation and removal, not an actual loading failure. This is a browser API defined by HTML, not an ECMAScript language feature; Node 24 does not establish its availability.

Examples

(() => {
  const element = document.createElement('img');
  element.onerror = function (event) {
    console.log(`${event.type}: ${event.target === element}`);
  };
  element.dispatchEvent(new Event('error'));
  element.onerror = null;
  element.dispatchEvent(new Event('error'));
})();

Result

error: true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources