访问自定义元素的子节点?

Accessing childNodes of custom elments?

这可能有点令人困惑。我正在尝试从我的自定义元素访问 innerHTML 或 childNodes。是否可以从 Web 组件导入文件访问原始 DOM 结构?在附加阴影之前?

在下面的示例中,我试图从我的 jookah-gallery 导入文件中访问两个 jookah-images 的 src。

免责声明:在影子 DOM 和 Web 组件方面,我完全是菜鸟,所以如果有任何重大错误,我很乐意理解原因。感谢您的帮助!

index.html

<jookah-gallery>
    //here
    <jookah-image class="gallery-image" src="http://merehead.com/blog/wp-content/uploads/gradient-design.jpeg">
    <jookah-image class="gallery-image" src="https://webgradients.com/public/webgradients_png/035%20Itmeo%20Branding.png">
</jookah-gallery>

为 jookah-gallery 导入文件:

(function(owner) {

    class jookahGallery extends HTMLElement {

        constructor() {

            super();

            //this returns false
            if (this.hasChildNodes()) {
                console.log('there are nodes')
            }else{
                console.log('NO nodes')
            }

            //shadow DOM attach
            const shadowRoot = this.attachShadow({mode: 'open'});
            const template = owner.querySelector('#jookah-gallery-template');
            const instance = template.content.cloneNode(true);
            shadowRoot.appendChild(instance);


        }

        // ---------------- object events -------------------------//

        connectedCallback() {
        }

        render(){
        }

        disconnectedCallback(){
        }

        attributeChangedCallback(){
        }

        // ---------------- methods ------------------------//


    }

    customElements.define('jookah-gallery', jookahGallery);

})(document.currentScript.ownerDocument);

根据规范,您不应该在 Web 组件的构造函数中检查、更改、添加和 children。

https://w3c.github.io/webcomponents/spec/custom/#custom-element-conformance

相反,您需要将 children 的读数移动到连接的回调中:

class jookahGallery extends HTMLElement {
  constructor() {
    super();
    this._childrenRead = false;

    const shadowRoot = this.attachShadow({mode: 'open'});
    const template = document.createElement('template');
    template.innerHtml = `Place your template here`;
    const instance = template.content.cloneNode(true);
    shadowRoot.appendChild(instance);
  }

  connectedCallback() {
    if (!this._childrenRead) {
      this._childrenRead = true;

      if (this.hasChildNodes()) {
          console.log('there are nodes')
      }else{
          console.log('NO nodes')
      }
    }
  }
}

customElements.define('jookah-gallery', jookahGallery);

你也可以在使用插槽时使用<slot> to embed your children. But there are some CSS issues you need to be aware of

Remember that shadowDOM is not supported in all browsers and is not a simple polyfill. So if you are only working on Chrome and Safari, go for it. If you are planning to support a broader range of browsers then you might not want to use ShadowDOM just yet.

https://alligator.io/web-components/composing-slots-named-slots/

另请在此处阅读更多内容: