HTML5 shadow dom example

HTML5 shadow dom is part of Web components. It is currently in draft stage and supported by Chrome. It can also be compared with react virtual dom. Here is a basic shadow dom example using HTML5 template.

<div id="name">Bob</div>
<template id="nameTemplate">
    Hi! My name is
    <span style="color:red;"><content></content></span>
var shadow = document.querySelector('#name').createShadowRoot();
var template = document.querySelector('#nameTemplate');
var clone = document.importNode(template.content, true);

Few points to note

  1. Here is the inspect element outcome in Chrome. Note that we are seeing an extra entry for #shadow-root.
  2. .createShadowRoot() is used to create shadow root. The moment it is created, it shadows its host element.
  3. We used HTML5 template to populate shadow root. But we could have also used any valid DOM object. But typically one would use template for this purpose.
  4. The <content></content> in template is replaced by host element content.

Specification and Browser compatibility

Shadow DOMW3C Working DraftDOM
Yes 35+ NoNoNoNoYes 22+
Android ChromeAndroid FirefoxiOS SafariIE MobileOpera Mobile
Yes 47+ NoNoNoYes 33+
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments