Search code examples
javascriptshadow-domcustom-element

Use of third-party scripts in shadow DOM


I'm in the middle of developing custom elements for basic reusable controls (e.g. buttons, menus, data tables etc.) I'm aware of the browser support for custom elements and shadow DOMs, but I'm doing good with the available polyfills in general.

For some custom elements I use third-party scripts for extra functionality but sometimes they don't work as intended when they have to manipulate the DOM in some way.

That happens every time an external script wants to search for an element by class or id. Obviously the call

document.getElementById (id)

or

document.getElementsByClassName (class)

doesn't work because the element with the id or class cannot be found in the global DOM but in the shadow DOM.

As far as I know, you can't give the document variable a new reference in javascript.

So, is there a solution to this problem without parsing the whole script and rewriting it to become usable in a shadow DOM context?

EDIT: It's not about getting elements from shadow DOMs in general but how 3rd-party scripts can be used that don't know that they have to search in the shadow DOM they are called from and not in the main DOM. As pointed out in the comments by CBroe.


Solution

  • A workaround is to pull the element the 3rd party library needs to catch out of the Shadow DOM.

    <your-element>
      <div id="visible-id" class="visible-class"></div>
    </your-element>
    

    And insert it in the Shadow DOM using the <slot> element.

    Note: I've used a direct, HTML, example but you can insert the callable element by script when your custom element is created:

    connectedCallback () {
        this.innerHTML = '<div id="visible-id"></div>'
    }  
    

    Of course it's not really in the Shadow DOM but it will work with most of the 3rd-party libraries.

    You could also choose not to use Shadow DOM at all depending on your needs.