Last Updated: February 25, 2016
· steveniseki

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


<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>

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);

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.


Google's Polymer

<b>More info</b>


custom elements

web components

Say Thanks

2 Responses
Add your response


Nice brief introduction, thanks!

over 1 year ago ·

This is awesome

over 1 year ago ·