i trying learn how use web components (without use of polymer) using latest stable chrome 52 (i have tried webcomponents.js polyfill on chrome 52). however, when seem error queryselector. when attempt grab (admittedly poorly named template id) in console via document.queryselector('#template')
null , unable find it.
i using this guide albeit es6 syntax. (i tried direct copy , paste , had same issue)
i tried search within shadowdom, didn't exist there either.
view.html
<template id="template"> <style> </style> <div class="container"> <h1>wzview</h1> </div> </template> <script> "use strict"; class wzview extends htmlelement { createdcallback () { var root = this.createshadowroot(); var template = document.queryselector('#template'); root.appendchild(document.importnode(template.content, true)); } } document.registerelement('wz-view', wzview); </script>
index.html
<!doctype html> <html> <head> <!--<script src="/bower_components/webcomponentsjs/webcomponents.js"></script>--> <link rel="import" href="view.html"> </head> <body> <wz-view></wz-view> </body> </html>
console:
view.html:16 uncaught typeerror: cannot read property 'content' of null > document.queryselector('#template') null
in <script>
s inside imported html, don't use document.queryselector(...)
.
use:
// while inside imported html, `currentdocument` should used instead of `document` var currentdocument = document.currentscript.ownerdocument; ... // notice usage of `currentdocument` var templateinsideimportedhtml = currentdocument.queryselector('#template');
example (fixing example in question):
var currentdocument = document.currentscript.ownerdocument; // <-- added line class wzview extends htmlelement { createdcallback () { var root = this.createshadowroot(); var template = currentdocument.queryselector('#template'); // <-- changed line root.appendchild(document.importnode(template.content, true)); } }
compatibility:
only ie 11 won't support it. browsers (including edge) implement it, , ie 10 , below there polyfill.