Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select element within shadow root

I want to change a property in element hidden within shadow root. Due to the nature of a project I can't refer to document in JS directly, I can only use custom class (which doesn't work with shadow root) or jQuery, but I don't know how to write a path to the element.

The element does not have "part" so I can't use it in selector.

What I've already tried - I selected last element above shadow and referenced its shadowRoot, then I tried to find encapsulated element by its id. I was testing it in devtool, so far with no success.

$("#root_ptcschartline-7-bounding-box".shadowRoot).find("#chart-line")
  .css('padding','100px');

html snippet:

like image 549
JakubJ Avatar asked Jan 25 '26 15:01

JakubJ


1 Answers

If you are the Web Component author

Learn about ::part https://developer.mozilla.org/en-US/docs/Web/CSS/::part

access with .shadowRoot (on mode:"open" Web Components)

No need for jQuery selectors since IE9 was released... in 2011

[element].querySelector( selector ) uses the same notation

  • let div = document.querySelector("#root_ptcschartline-7-bounding-box");
    gets you the <div>

  • let chartLine = div.querySelector("ptcs-chart-line");
    gets you the <ptcs-chart-line> element

  • let shadow = chartline.shadowRoot;
    gets you the shadowRoot reference

  • let layout = shadow.querySelector("#chart-layout")
    gets you the <ptcs-chart-layout> element

all combined

Note! This will only work for #shadow-root (open) Not for #shadow-root (closed)

let layout = document
               .querySelector("#root_ptcschartline-7-bounding-box ptcs-chart-line")
               .shadowRoot
                   .querySelector("#chart-layout");

layout.style.padding = "100px";  

Document.querySelector() docs on MDN.

like image 188
Danny '365CSI' Engelman Avatar answered Jan 27 '26 06:01

Danny '365CSI' Engelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!