Jim
Jim

Reputation: 829

How to use js to query shadow dom element in Polymer?

I know how to query shadow dom element in <style> tag,but i want to use data-bind dynamically change the style,data-bind can not be applied in <style> in Polymer,so i should make it happen in js.For example,i use core-scroll-header-panel component, i can query its background style using:

<style>
    core-scroll-header-panel::shadow #headerBg {
          background: #5cebca;
        }

</style>

but how can implement it in js?

Upvotes: 3

Views: 1480

Answers (2)

vinyll
vinyll

Reputation: 11409

Here's the way to select your element:

var shadow = document.querySelector('core-scroll-header-panel').shadowRoot;
var header = shadow.querySelector('#headerBg');

Note that it will return one single element. If you need to loop over multiple element you may use querySelectorAll as you probably know.

You can then change your background color as normal:

header.style.backgroundColor = "#5cebca";

However, changing a color in directly in JavaScript is not adviced and you should use CSS for that.

header.className = "my_css_class";

Note that it will return one single element. If you need to loop over multiple element you may use querySelectorAll as you probably know.

Upvotes: 1

Jim
Jim

Reputation: 829

I have tried it out :

document.querySelector('core-scroll-header-panel::shadow #headerBg');

and is there any else solutions?

Upvotes: 0

Related Questions