我想创建新元素并追加到#containerconnectedCallback部分中。我使用this.shadowRoot.querySelector("#container")选择元素,但是它总是返回null。如何在阴影根中选择元素?



<!DOCTYPE html>
<html lang="en">

<head>
  <script src="https://polygit.org/components/webcomponentsjs/webcomponents-loader.js"></script>
  <link rel="import" href="https://polygit.org/components/polymer/polymer-element.html">
</head>

<body>
  <dom-module id="dom-element">

    <template>
        <div id="container">
          <p>I'm a DOM element. This is my shadow DOM!</p>
        </div>
      </template>

    <script>
      class DomElement extends Polymer.Element {
        connectedCallback() {
          this.attachShadow({
            mode: "open"
          })

          console.log(this.shadowRoot.querySelector("#container"))
        }

        static get is() {
          return "dom-element";
        }
      }
      customElements.define(DomElement.is, DomElement);
    </script>

  </dom-module>

  <dom-element></dom-element>
</body>

</html>

最佳答案

Polymer.Element已经附加了影子根,因此您无需在connectedCallback()中自己进行操作。更重要的是,您的自定义connectedCallback()必须调用super.connectedCallback()才能正常操作。它看起来应该像这样:

connectedCallback() {
  super.connectedCallback(); // DO THIS
  // this.attachShadow(...)  // DON'T DO THIS

  console.log('container', this.shadowRoot.querySelector("#container"));
}


demo

07-24 09:30