Templates and the Shadow DOM

The shadow DOM is currently only supported by Chrome and Opera.

A recent goal of mine was to develope a deeper understanding of html and the DOM, past the marking up of divs. Having seen their use in Meteor, I created the Atomsphere page to better understand templates. I put together this small study here to add the shadow DOM into the mix. The picture of the dog on the top right of this page is a shadow DOM widget. You can update the image and text by clicking one of the dog images below.

First, I created a (very simple) template to pass my images into.

<template id="dog-matrix-template">
  <a href=""><img src="" alt="" class="matrix-img"><a>

Next, I created a widget template and shadow host element.

<div id="widget-host">
  <div class="host-con">
    <img src="" alt="" class="host-img">
  <span class="host-info">This shouldn't show.</span>

<template id="widget-template">
    .foo {
      color: #a25;
      display: inline-block;
      margin: 10px 0;
    <content select=".host-con"></content>
  <span class="foo">
    <content select=".host-info"></content>

Finally, a little javascript magic to populate the image group, initiate the widget, and allow the ability to seclect a new image for the widget by clicking from the image group

// Matrix Formation

(function() {

  var t = document.querySelector("#dog-matrix-template");
  var dog;
  var clone;
  for (var i = 0; i<dogs.length; i++) {
    dog = dogs[i];
    t.content.querySelector("img").src = dog.src;
    t.content.querySelector("img").alt = dog.alt;
    clone = document.importNode(t.content, true);

// Widget Formation

(function() {

  var shadow = document.querySelector("#widget-host").createShadowRoot();
  var t = document.querySelector("#widget-template");
  var clone = document.importNode(t.content, true);

  // default image and text
  document.querySelector(".host-img").src = dogs[5].src;
  document.querySelector(".host-img").alt = dogs[5].alt;
  document.querySelector(".host-info").textContent = dogs[5].alt;


// Widget Interaction

$("#dog-matrix a").on("click", function(e) {
  $("#widget-host img").attr("src", $(this).children().attr("src"));

Hope I didn't mess this one up.

This shouldn't show.
Eric Williams