JavaScript Extending Native Elements

Download JavaScript for free

Example

It's possible to extent native elements, but their descendants don't get to have their own tag names. Instead, the is attribute is used to specify which subclass an element is supposed to use. For example, here's an extension of the <img> element which logs a message to the console when it's loaded.

const prototype = Object.create(HTMLImageElement.prototype);
prototype.createdCallback = function() {
  this.addEventListener('load', event => {
      console.log("Image loaded successfully.");
  });
};

document.registerElement('ex-image', { extends: 'img', prototype: prototype });
<img is="ex-image" src="http://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png" />
Registering New Elements