Search code examples
polymershady-dom

Traversing into Local DOM from Outside of the Component Using JavaScript


I am trying to access the local DOM elements from outside of the Polymer components using JavaScript. In the past I could use the document.querySelector and select the shadowDOM elements using the ::shadow selector.

Currently, I understand that the local DOM is implemented as "shady DOM". How do I access the local DOM elements in that case?


Solution

  • Let's say you have a component like the one below, and you need to get to the div element from outside of the component:

    <dom-module id="my-element">
      <template>
        <div id="container"></div>
      </template>
      <script>
        Polymer({is: 'my-element'});
      </script>
    </dom-module>
    

    And on your page, you place the element as:

    <my-element id="myElement"></my-element>
    

    The first thing we do is get a reference to the custom-element element in our page JS:

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

    Now, to get to the div we have two options. The first one is Polymer's handy automatic node finding. This makes it so that every element in your component (that exists and is stamped prior to ready) is added to this.$.<my-id>. That makes it easy to reach from the outside, like so:

    var div = myElement.$.container;
    

    But if the div does not have an ID, or is otherwise unreachable like this, you can use Polymer's own querySelector attached to the element itself, like so:

    var div = myElement.querySelector('div');
    

    I have to say, though, that both of these should really be "last resort" methods for interacting with a component. Often rather than exposing a DOM element directly, you should instead expose a method or property that drives that component's DOM. I recommend you drop by the Polymer Slack chat and let us know what you're looking to do, and we can give you some good options.