0

Let's say I have html element with shadow root.

<my-element>
#shadow-root
<div class='need-target-this' />
</my-element>

How can I target div inside shadow root?

I've tried to use

:host(my-element.need-target-this)

But it didn't help. What am I missing here?

Alex
  • 455
  • 1
  • 5
  • 14

2 Answers2

1

customElements.define("my-element",class extends HTMLElement{
  constructor(){
    super().attachShadow({mode:"open"}).innerHTML = `
    <style>
      .target { background:hotpink; border: 5px dashed green }
      ::slotted(span) {
        color : red;
      }
    </style>
    <slot name="title"></slot>
    <span part="mytarget" class='target' />`;
  }
  connectedCallback(){
    this.shadowRoot.querySelector("span").innerHTML = `Web Component!`;
  }
});
<style>
  * { font: 42px Arial }
  span {
    background:gold; /* slot content styled by Global CSS! */
  }
  .target { border: 5px solid blue } /* does NOT style shadowDOM! */
  
  my-element::part(mytarget) {
    font-size: 150%;
  }
</style>

<my-element class="target"><span slot="title">Hello</span>

</my-element>
Danny '365CSI' Engelman
  • 16,526
  • 2
  • 32
  • 49
  • Thanks for your answer, but it wouldn't help. I'm using 3rd party package for Next.js, that's why I need override styles, forgot to mention it. Anyway, thanks for your time – Alex Jan 23 '23 at 16:30
  • If you have script access you can inject anything of the above – Danny '365CSI' Engelman Jan 23 '23 at 16:33
  • I will go with ```document.querySelector``` and overriding styles solution, but thank you anyway. Was just wondering if it could be done with pure CSS. – Alex Jan 23 '23 at 16:53
0

In case it will help some one: I wrapped my element with div added ref and then went

const shadow = ref.current.querySelector('my-element').shadowRoot

const target = shadow?.querySelector('.need-target-this')

target.style.whatever = 'value';

Alex
  • 455
  • 1
  • 5
  • 14