I defined a component with polymer like this:
<polymer-element name="my-component">
<template>
<div id='test'>CONTENT</div>
</template>
</polymer-element>
Now I want to access the shadow dom, for example: to get the content of div id='test'
var x = $("div#test").html();
The given code doesn't work. Can I access the shadow dom with jquery?
We can only access the shadow DOM by the reference returned by attachShadow (and probably hidden inside a class). Browser-native shadow trees, such as <input type="range"> , are closed. There's no way to access them.
What is the shadow DOM? In our introduction article, we said that the shadow DOM was “capable of isolating CSS and JavaScript, almost like an <iframe> .” Like an <iframe> , selectors and styles inside of a shadow DOM node don't leak outside of the shadow root and styles from outside the shadow root don't leak in.
By using the Shadow DOM. Nowadays, most frontend web developers build their UI with well-known libraries and frameworks such as React, Angular, Vue, and so on. Maybe many developers have almost forgotten how to dynamically create HTML elements by accessing the Document Object Model (DOM).
The :host selector allows to select the shadow host (the element containing the shadow tree).
No, not outside of the Polymer element.
After reading up on Polymer, it looks like you can only have access to the shadow-DOM of Polymer elements in scripts within the Polymer element. The Polymer docs on Automatic node finding say:
Every node in a component’s shadow DOM that is tagged with an id attribute is automatically referenced in the component’s this.$ hash.
This means you can add a <script>
tag as a sibling to <template>
where this.$.test
will be the element you want.
<polymer-element name="my-component">
<template>
<div id='test'>CONTENT</div>
</template>
<script>
Polymer('my-component', {
logNameValue: function () {
console.log('polymer element', this.$.test);
console.log('jQuery wrapper of polymer element', $(this.$.test));
}
});
</script>
</polymer-element>
You can use $('body /deep/ your-selector')
pattern to pierce through shadow DOM and get Jquery to work inside it.
update: So far I have only managed to make this work on chrome for desktop. I believe, other browsers do not support the /deep/ combinator.
update 2: /deep/
combinator is deprecated and should not be used anymore. It is scheduled to be removed from Chrome.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With