Cameron
Cameron

Reputation: 28793

Call LitElement method from outside the element

I have a simple LitElement component like so:

class MyElement extends LitElement {

  constructor() {
    super();
  }

  customMethod(data) {
    // do something with the passed parameter
  }

  render() { 
    return html`<div id="element"></div>`;
  }
}

customElements.define('my-element', MyElement);

And I want to be able to call that customMethod from outside of my element.

So for example if I add the element to web page like so:

<my-element></my-element>

I then want to be able to add some JavaScript to the page and call that customMethod.

I tried:

var element = document.getElementById('element');

element.shadowRoot.customMethod('example data');

But it claims it's not available... How can I call a method on an instance of LitElement?

Upvotes: 2

Views: 3671

Answers (2)

Ovidijus Parsiunas
Ovidijus Parsiunas

Reputation: 2732

I had a very similar problem and the existing answers did not seem to fix it. The reason for my issue was caused by the fact that LIT Element scripts are exported as modules, meaning that they are loaded and executed after the initial DOM has been parsed. So if you are using a script to access the public method - make sure that it is also in a module (or you can alternatively place the code into an appropriate timeout).

So when defining an element in LIT Element as follows:

@customElement('my-element')
export class MyElement extends LitElement {
  @state()
  text = '';

  customMethod(data) {
    this.text = 'Custom method was called!';
  }

  render() {
    return html`<div id="element">${this.text}</div>`;
  }
}

And adding a script in my index.html page:

<my-element id='element'></my-element>
<script type="module">
  const element = document.getElementById('element');
  element.customMethod();
</script>

Make sure that the script tag contains type="module". Otherwise you will see the following error in the console: Uncaught TypeError: element.customMethod is not a function

Link to LIT Element Playground.

Also, here is a great article that explains how scripts are loaded in detail.

Upvotes: 0

vals
vals

Reputation: 64164

You don't need to use shadowRoot in the call :

var element = document.getElementById('element');

element.customMethod('example data');

but you need to be able to locate your element

<my-element id='element'></my-element>

Upvotes: 6

Related Questions