16th July 2023

Calling static methods from custom components

To call a static method of one custom element from another file, you need to ensure that the custom elements are registered and accessible in the global scope. Here's a step-by-step guide on how to achieve this:

Let's assume you have two custom elements defined in separate JavaScript files:

  1. customElementA.js defining Custom Element A:
class CustomElementA extends HTMLElement {
  // ... other code for the element

  static staticMethodA() {
    console.log("Static method of Custom Element A was called!");

customElements.define('custom-element-a', CustomElementA);
  1. customElementB.js defining Custom Element B:
class CustomElementB extends HTMLElement {
  // ... other code for the element

  // Static method of Custom Element B trying to call a method of Custom Element A
  static callStaticMethodOfA() {

customElements.define('custom-element-b', CustomElementB);
  1. In your HTML file (index.html), you should import both JavaScript files using <script> tags. Make sure to include the Custom Element A script before Custom Element B script so that it is registered first:
<!DOCTYPE html>
  <title>Custom Elements</title>
  <!-- Your HTML content with custom elements here -->
  <script src="path/to/customElementA.js"></script>
  <script src="path/to/customElementB.js"></script>

With this setup, when CustomElementB.callStaticMethodOfA() is called, it will invoke the staticMethodA() of CustomElementA. Please ensure that the paths to the JavaScript files are correctly specified in the <script> tags. Also, make sure that the HTML file (index.html) is being loaded properly in the browser.

Note that when you load the HTML page and the custom elements are registered, they will be accessible in the global scope.