Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. HTMLElement
  4. error

HTMLElement: error event

Theerror event is fired on an element when a resource failed to load, or can't be used. For example, if a script has an execution error or an image can't be found or is invalid.

This event is not cancelable and does not bubble.

Syntax

Use the event name in methods likeaddEventListener(), or set an event handler property.

js
addEventListener("error", (event) => { })onerror = (event) => { }

Event type

The event object is aUIEvent instance if it was generated from a user interface element, or anEvent instance otherwise.

Event UIEvent

Examples

Live example

HTML

html
<div>  <button type="button">Generate image error</button>  <img src="bad-image.jpg" alt="I don't exist" /></div><div>  <label for="eventLog">Event log:</label>  <textarea    readonly       rows="8"    cols="30"   ></textarea></div>
body {  display: grid;  grid-template-areas: "control log";}.controls {  grid-area: control;  display: flex;  align-items: center;  justify-content: center;}.event-log {  grid-area: log;}.event-log-contents {  resize: none;}label,button {  display: block;}button {  height: 2rem;  margin: 0.5rem;}img {  width: 0;  height: 0;}

JavaScript

js
const log = document.querySelector(".event-log-contents");const badImg = document.querySelector(".bad-img");badImg.addEventListener("error", (event) => {  log.textContent += `${event.type}: Loading image\n`;  console.log(event);});const imgError = document.querySelector("#img-error");imgError.addEventListener("click", () => {  badImg.setAttribute("src", "i-dont-exist");});

Result

Specifications

Specification
UI Events
# event-type-error
HTML
# event-error

Browser compatibility

See also

  • Related events

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp