Link Search Menu Expand Document

<script extend> tag

The “script extend” tag is has a special behavior. You will create a class extending the component, that’s how you extend your full component with advanced script.

To do so extend the Lego class, that’s a naming convention:

export default class extends Lego {
  …
}

From there you can catch connected() events, changed() when the state is updated, override setAttributes() and all other Lego or HTMLElement properties.

It’s also a great place to define custom events or custom methods for your component that are accessible from the outside:

/bricks/my-element.html

<script extend>
  export default class extends Lego {
    getStatus() {
      return `you are requesting status of ${ this.nodeName }`)
    }
    connected() {
      console.info('the component is connected to the dom')
    }
  }
</script>

/bricks/index.html

<my-element id="elem"></my-element>
<script>
  console.debug(document.querySelector('#elem').getStatus())
</script>

Accessing the component’s DOM

Even if it’s not the most recommended way it might occur that you need to access a DOM element from the script tag.

In which case the shortcut this.document will gain you access to the DOM, wether it’s the Shadow DOM (default) or you toggled to Light DOM (overriding).

this.document has all the native methods you may expect from a document such as querySelector, getElementById, querySelectorAll…

export default class extends Lego {
  init() {
    console.log(this.document.querySelectorAll('a'))
  }
}