Getting a node list by querySelectorAll()

徘徊边缘 提交于 2019-12-13 17:27:31

问题


Given the following sample code:

import { LitElement, html, css } from 'lit-element';

class ItemsDisplay extends LitElement {

    static get styles() {...}
    static get properties {...}

    constructor () {
        super();
        ...
    }

    render {
        return html`
            ${this.items.map((item, index, array) => html`
                <div class="name">
                    ...
                </div>
            `)}        
        `;
    }
}

What is the appropriate way to select all nodes with class "name"?

I have tried the following ways, but failed; all times nodesList was undefined:

  • Inside constructor:
  this.nodesList = this.shadowRoot.querySelectorAll(".name");
  • Using:
  firstUpdated(changedProperties) {
      return this.nodesList = this.shadowRoot.querySelectorAll(".name");
  }
  • Inside a custom function:
  getNodesList() {
      let nodesList = this.shadowRoot.querySelectorAll(".name");
      ...
  }

I have also tried with:

connectedCallback() {
    super.connectedCallback();
    return this.nodesList = this.shadowRoot.querySelectorAll(".name");
}

Looking forward reading the solution.

Tia


回答1:


You shouldn't try to access DOM node in the constructor, because they won't be available yet.

The best place to query DOM nodes is the firstUpdated() lifecycle callback, which is called after the first time your element's DOM has been updated. You also don't need to return it from firstUpdated, you can just do something like:

  firstUpdated(changedProperties) {
    // Store a reference to the form element for easy access
    this.$someNode = this.shadowRoot.querySelector('div');

You can see some examples of this over at: https://stackblitz.com/edit/open-wc-lit-demos?file=02-intermediate%2F05-querying-dom.js

https://stackblitz.com/edit/open-wc-lit-demos?file=02-intermediate%2F01-first-updated.js

Additionally, if you're using TypeScript, you can use the query decorator:

@query('div')
myDiv;

More info: https://github.com/Polymer/lit-element/blob/master/src/test/lib/decorators_test.ts#L326



来源:https://stackoverflow.com/questions/54869489/getting-a-node-list-by-queryselectorall

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!