Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I access the shadow DOM using jQuery?

Tags:

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?

like image 724
mica Avatar asked Jan 19 '14 15:01

mica


People also ask

How do I access shadow DOM?

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.

Does shadow DOM isolate JavaScript?

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.

What frameworks use shadow DOM?

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).

Which selector can work for shadow DOM elements?

The :host selector allows to select the shadow host (the element containing the shadow tree).


2 Answers

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>
like image 55
Henry Blyth Avatar answered Oct 16 '22 04:10

Henry Blyth


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.

like image 24
David Aroesti Avatar answered Oct 16 '22 03:10

David Aroesti