How to access imported html elements from script inside imported html

I want to create a custom element that will self-register when importing html.

order element.html:

<html>
  <...>
  <body>
    <template id="myTemplate">
    </template>
  </body>
  <script src="my-script.js">
</html>

my- script.js

let customElementPrototype = Object.create(HTMLElement.prototype);
customElementPrototype.createdCallback = function () {
  // somewhere here i want to access <template> to insert it in element
  // I've tried document.querySelector("#myTemplate") and
  // document.currentScript.ownerDocument.querySelector.querySelector("#myTemplate")
  // they don't work either, result of querySelector is null
}
document.registerElement("custom-element", customElementPrototype);

Using:

<html>
<head>
  <link rel="import" href="custom-element.html">
</head>
<...>
+4
source share
1 answer

Inside the createdCallbackcontext is this custom-element, not ownerDocument.. You can see this in the console.log(this);inside createdCallback, which logs (from my plunker example ):

<div is="custom-element">
</div>

my-script.js ownerDocument . DOM, DOM HTML. .

var mainDoc = document.currentScript.ownerDocument;

my-script.js (script.js ):

var mainDoc = document.currentScript.ownerDocument;

var CustomElementPrototype = Object.create(HTMLElement.prototype);
CustomElementPrototype.createdCallback = function () {
  console.log(this); //the div 
  //import the contents of the template
  var clone = document.importNode(mainDoc.querySelector('#myTemplate').content, true);
  //append template to div
  this.appendChild(clone);
};

document.registerElement("custom-element", {
    prototype: CustomElementPrototype,
    extends: 'div'
});

, ( mainDoc):

<html>
  <body>
    <script src="script.js"></script>
    <template id="myTemplate">
      hello world
      <br>
      from template
    </template>
  </body>
</html>

HTML, :

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <link rel="import" href="custom-element.html">
  </head>

  <body>
    <h1>Hello Plunker!</h1>
    <div is="custom-element"></div>
  </body>

</html>

https://plnkr.co/edit/jO3ci8vLxolHhvtGxJQ5

: http://webcomponents.org/articles/introduction-to-html-imports/

+4

Source: https://habr.com/ru/post/1626014/


All Articles