h8qrfa
Last Updated: February 25, 2016
·
1.206K
· steveniseki
Stevenm

custom html elements Shadow DOM

Custom Elements allow web developers to define new types of HTML elements with custom functionality.

<b>Defining new DOM elements</b>

Register a new html element with document.registerElement

var myApp = {};    
myApp.XFoo = document.registerElement('x-foo', {
  prototype: Object.create(HTMLElement.prototype)
});

define your element in markup as you would another html element

<x-foo></x-foo>

<b>Extend from other elements</b>

inherit from a button element

myApp.XButton = document.registerElement('x-button', {
  prototype: Object.create(HTMLButtonElement.prototype),
  extends: 'button'
});

markup for new x button element

<button is="x-button">

inherit from x foo element

// inherit from xFoo
myApp.XFooExtended = document.registerElement('x-foo-extended', {
  prototype: myApp.XFoo,
  extends: 'x-foo'
});

<b>Add properties and methods to provide functionality for an element</b>

add methods and properties to your custom x-foo element

// method
myApp.XFooProto.hello = function() {
  console.log('hello() called');
};

// writable property
Object.defineProperty(XFooProto, 'bar', { 
    value: 20,
    writable : true
});

<b>Creating elements from Shadow DOM with a template</b>

create a template to define the markup for your new element

<template id="foo-template">
  <p>I'm in Shadow DOM...</p>
</template>

add the element to the ShadowDOM of the element once the element is created

myApp.XFooProto = Object.create(HTMLElement.prototype);

// element created callback
XFooProto.createdCallback = function() {
  var shadow = this.createShadowRoot();
  var template = document.querySelector('#foo-template');
  var cloneTemplate = document.importNode(template.content, true);
  this.createShadowRoot().appendChild(cloneTemplate);
};

myApp.XFoo = document.registerElement('x-foo-shadow', {prototype: XFooProto});

<b>Browser support</b>

Chrome 31 is the first to have true support for the updated Custom Element spec.

<b>Polyfills</b>

Google's Polymer

<b>More info</b>

html5rocks

custom elements

web components

Say Thanks
Respond

2 Responses
Add your response

14197
D42a7264714dee5006b9c99d2567a320

Nice brief introduction, thanks!

over 1 year ago ·
14251

This is awesome

over 1 year ago ·