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">
  <div>
    Hi! My name is
    <span style="color:red;"><content></content></span>
  </div>
</template>
<script>
var shadow = document.querySelector('#name').createShadowRoot();
var template = document.querySelector('#nameTemplate');
var clone = document.importNode(template.content, true);
shadow.appendChild(clone);
</script>
refresh

Few points to note

  1. Here is the inspect element outcome in Chrome. Note that we are seeing an extra entry for #shadow-root.
    html5-shadow-dom-inspect-element
  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

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

Comments

Click here to write/view comments