Changing to local DOM from outside component with JavaScript
I am trying to access local DOM elements from outside of Polymer components using JavaScript. In the past, I was able to use document.querySelector
and select shadowDOM elements using a selector ::shadow
.
My current understanding is that the local DOM is implemented as a "shadow DOM". How can I access local DOM elements in this case?
source to share
Let's say you have a component like the one below and you need to navigate to an element div
from outside the component:
<dom-module id="my-element">
<template>
<div id="container"></div>
</template>
<script>
Polymer({is: 'my-element'});
</script>
</dom-module>
And in your page you will put the element like:
<my-element id="myElement"></my-element>
The first thing we do is get a link to an element custom-element
in our JS page:
var myElement = document.getElementById('myElement');
Now, to move on to div
, we have two options. The first is the "Polymer" automatic search node . This makes it so that every element in your component (which exists and is stamped before ready
) is appended to this.$.<my-id>
. This makes it easier to access from the outside, for example:
var div = myElement.$.container;
But if it div
doesn't have an ID or is otherwise unavailable, you can use your own <polymeric < querySelector
that belongs to the element itself, for example:
var div = myElement.querySelector('div');
I must say, however, that both should really be the "last resort" to interact with the component. Oftentimes, instead of directly acting on a DOM element, you should instead expose a method or property that manipulates the component's DOM. I recommend that you go to the Polymer Slack chat and tell us what you want to do and we can give you some good options.
source to share
In my case, this was not enough. 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 must add that I am a newbie when it comes to polymer, so I cannot explain why this worked for me and not for the code above. But I believe it was because I was using myElement inside a page, which is, after all, a custom element in itself.
source to share