Last Updated: February 25, 2016
·
2.928K
· 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

<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

2 Responses
Add your response

Nice brief introduction, thanks!

over 1 year ago ·

This is awesome

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside