Select element within shadow root
Asked Answered
F

3

12

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:

Fogged answered 26/2, 2021 at 11:15 Comment(1)
In the future, please post code as code not images ref: meta.#286051 may help you here.Androsphinx
P
19

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.

Parasite answered 27/2, 2021 at 13:56 Comment(0)
F
2

As I've mention I cannot use "document".

error message

Although this seems to do the trick:

$('#chart-layout', $('#root_ptcschartline-7-bounding-box ptcs-chart-line')[0].shadowRoot).css('padding');
Fogged answered 1/3, 2021 at 10:0 Comment(0)
L
-2
dom elemnt=document.querySelector('app-root').querySelector('ion-toast').shadowRoot.querySelector('.toast-container')


const element= await browser.executeScript("return document.querySelector('app-root').querySelector('ion-toast').shadowRoot.querySelector('.toast-container')", []);

    const ele=await $(element);
    console.log((await ele.getText()));
Letti answered 15/7 at 12:3 Comment(3)
Please format your codeAndrosphinx
And please add some separate text that explains the code and your answer.Kitten
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Eaglestone

© 2022 - 2024 — McMap. All rights reserved.