Skip to content

Instantly share code, notes, and snippets.

@philcon93
Last active December 15, 2016 06:27
Show Gist options
  • Save philcon93/4aae098af010efe8e0c2329a5aa8d153 to your computer and use it in GitHub Desktop.
Save philcon93/4aae098af010efe8e0c2329a5aa8d153 to your computer and use it in GitHub Desktop.
Web Components

Custom Elements

Element registration

Before you can use a custom element, it needs to be registered. Otherwise, the browser considers it an HTMLElement.

document.registerElement()

To register a new custom element in JavaScript, invoke document.registerElement() somewhere in the page. As before, custom elements built this way work just like standard elements.

var XFooPrototype = Object.create(HTMLElement.prototype);
XFooPrototype.createdCallback = function() {
  this.textContent = "I'm an x-foo!";
};

XFooPrototype.foo = function() {
  console.log('foo() called');
};

var XFoo = document.registerElement('x-foo', {
  prototype: XFooPrototype
});

After registration, you can construct an instance of your element just like standard DOM elements:

<x-foo></x-foo>

Custom Elements

Extending existing elements

If you want to inherit from a specialized form of HTMLElement (e.g. HTMLButtonElement), declare the type using the extends option when calling document.registerElement():

Example extending button:

var XFooButtonPrototype = Object.create(HTMLButtonElement.prototype);
XFooButtonPrototype.createdCallback = function() {
  this.textContent = "I'm an x-foo button!";
};

var XFooButton = document.registerElement('x-foo-button', {
  prototype: XFooButtonPrototype,
  extends: 'button'
});

If you've used extends to create a custom element that derives from an existing DOM element (e.g. something other than HTMLElement), use the is syntax:

<button is="x-foo-button"></button>

@philcon93
Copy link
Author

var proto = Object.create(HTMLElement.prototype, {
  createdCallback: {
    value: function() {
      var t = document.querySelector('#netoSearch');
      var clone = document.importNode(t.content, true);
      this.createShadowRoot().appendChild(clone);
    }
  }
});

document.registerElement('neto-search', {prototype: proto});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment