Polight/lego

Query selector

Closed this issue · 4 comments

echb commented

Hi, is there a way to access to a element like querySelector?

my element<\div>
<script> this.shadowRoot.querySelector?? Didn't work :( <script> Anyone?

Hey @echb,

this.document is a shortcut for accessing the current document, either the shadow dom (by default) or if you override to use the light dom.

this.document.querySelector() is therefore what you are looking for.
See an example here: https://gitlab.com/anthropedia/tci/professionals/-/blob/master/bricks/x-login.html#L20

echb commented

Hi, is there a way to access to a element like querySelector?

my element<\div>
<script> this.shadowRoot.querySelector?? Didn't work :( <script> Anyone?

@vinyll
Thanks it worked on binding events!! Any idea how to use it without binding events, like Inside init method?

init(){
query selector...
}

I tried and didn't worked :(

I'm not quite sure what you're trying to achieve here.

You may read about binding events which may be easier and clearer than querying the dom.

If for some reason you need to access the dom and bind events then, something like the following could be an approach:

export default class extends Lego {
  connected() {
    this.document.querySelector('button').addEventListener('click', (event) => {
      console.debug('button was clicked', event.target)
    })
  }
}