Search code examples
javascriptstringclassweb-componentcustom-element

How to access a class if you have a string of its name in javascript?


In javascript, if I have 2 strings myApp and my-app and was told that myApp is really a name of a class that extends HTMLElement, and my-app is that class's tagname, how can I use JavaScript to verify that (assuming that the class is already defined)?

Basically the test should pass if this was really defined already

class myApp extends HTMLElement {
    constructor() {
        super();
    }
}

customElements.define('my-app', myApp); 

Basically, it needs to check that myApp is a class and does extend HTMLElement (though it's possible it may extend something else, such as Polymer.Element, and on wards, but eventually, it must extend HTMLElement).

And then secondly, it must check my-app is the tag name of that class.

How can this be done in javascript?

I tried eval("myApp") but it did not work.


Solution

  • You can use customElements.get() to get the custom element class from its tag name.

    class myApp extends HTMLElement {
      constructor() {
        super()
      }
    }
    customElements.define( 'my-app', myApp )
    
    console.log( customElements.get( 'my-app' ) === myApp )  //true