3

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?

TylerH
  • 20,799
  • 66
  • 75
  • 101
zen
  • 257
  • 3
  • 16

2 Answers2

2

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.

Zikes
  • 5,888
  • 1
  • 30
  • 44
  • 1
    hi Zikes. Thanks for the solution. I have issue joining the Polymer Slack, it seems like i need to be invited. – zen Jul 06 '15 at 06:24
0

This was not enough in my case. What helped me in the end was the answer above, combined with this: shadowRoot.querySelector

var myElement = this.shadowRoot.querySelector('#myElement');
var div = myElement.shadowRoot.querySelector('div');

I have to add that i am a beginner when it comes to polymer so I cant really explain why this worked for me and not the code above. But I believe this was the case because I used myElement inside a page which is in the end a custom element by itself.

Community
  • 1
  • 1
Niklas
  • 1,142
  • 16
  • 33