Raj
Raj

Reputation: 3061

How do I fix this custom element <content> element implementation?

I am trying to create a "transcluded" version of a custom element where when it wraps some arbitrary HTML it will selective pick content from that wrapped mark-up and render it within its shadow DOM body. Like so:

<tab-content>
      .....
                 <span class="name">John</span>
                 <span class="email">Email</span>
      .....
 </tab-content>

When I use the following code, I see the content in the shadow DOM render as-is when this code is run.

What could I be doing wrong here?

index.html

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<link href="import.html" rel="import" />
</head>

<body>

<tab-content>
<div id="test">
   <span class="name">
	   John
   </span>
   <span class="email">
	   [email protected]
   </span>
</div>
</tab-content>

</body>
</html>

<head>
	<link href="style.css" type="text/css" rel="stylesheet">
</head>
<template id="tag">
  <div class="content">
     This is the shadow DOM content. Your name is <content select="#test .name"></content> and email is <content select="#test .email"></content>
  </div>
</template>

<script>
var proto = Object.create(HTMLElement.prototype);
var hostDocument = document.currentScript.ownerDocument;
proto.createdCallback = function () {
	var root = this.createShadowRoot();
	root.appendChild(hostDocument.getElementById("tag").content);
}

var tab = document.registerElement("tab-content", {
	prototype: proto
});
</script>

style.css

@charset "UTF-8";
/* CSS Document */


.test-content {
	background-color: #f00;
	widthL 200px;
	height: 300px;
}

Upvotes: 0

Views: 103

Answers (1)

Robin Carlo Catacutan
Robin Carlo Catacutan

Reputation: 13679

I have made it like this to work :

From :

var root = this.createShadowRoot();

to :

  var host = document.querySelector('#test');
  var root = host.createShadowRoot();

import.html

<head>
    <link href="style.css" type="text/css" rel="stylesheet">

</head>
<template id="tag">
  <div class="content">
     This is the shadow DOM content. Your name is <content  select=".name"></content> and email is <content select=".email"></content>
  </div>
</template>

<script>
var proto = Object.create(HTMLElement.prototype);
var hostDocument = document.currentScript.ownerDocument;


proto.createdCallback = function () {
  var host = document.querySelector('#test');
  var root = host.createShadowRoot();

  var template = hostDocument.querySelector('#tag');
  root.appendChild(template.content); 

}

var tab = document.registerElement("tab-content", {
    prototype: proto
});

</script>

Running code http://plnkr.co/edit/sWgrWoyq3nlvGI5rTojr?p=preview

Upvotes: 1

Related Questions