Search code examples
javascriptweb-component

How to select all custom element that inherit from a specific javascript class


right now I'm trying to have fun with the webComponent. I have created a component that is supposed to represent a mother class to all my other translatable components. it works as I want at the moment, but I would like a way to select all the elements of the current document that inherits from this mother class. something like:

document.getElementsByTagName('lsp-motherComposant');

doesn't works.

index.html

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>WebComponentTest</title>
        <!-- motherComponent -->
        <link rel="import" href="components/lsp-translatable/lsp- 
        translatable.html" />
        <!-- child Component -->
        <link rel="import" href="components/lsp-button/lsp-button.html" />
    </head>

    <body>
        <select id="lang">
            <option value="fr" selected>fr</option>
            <option value="en">en</option>
            <option value="zh">zh</option>
        </select>

        <lsp-button i18n="events" width="33%" gradient color1="0,0,0,0" 
        color2="128,0,128,1" direction="left"></lsp-button>

        <script type="text/javascript">
             window.onload = function(){
             document.getElementsByTagName('lsp-translatable');
             // => empty node list

             };
         </script>
    </body>

    </html> 

lsp-translatable.js:

class LspTranslatable extends HTMLElement {//some stuff}
customElements.define('lsp-translatable', LspTranslatable);

lsp-button.js:

class LspButton extends LspTranslatable {//some stuff}
customElements.define('lsp-button', LspButton);

Solution

  • This won't help you in production code but it's a development version of what you are looking for.

    Chrome DevTools has a developer command queryObjects that will return all instances of a class. In Chrome DevTools you could run the following:

    queryObjects(LspTranslatable);