Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS selector for shadow root or all top level elements in shadow root

I need a selector for usage in css inside a shadow root, which selects all children (but not grand children) of the shadow root, no matter what tag they are and without giving them an ID.

In the example below, SPAN,A,P and DIV should get a red border, but SPAN IN DIV not.

<my-element>
  #shadow-root
    <span>SPAN</span>
    <a>A</a>
    <p>P</p>
    <div>
      DIV
      <span>SPAN IN DIV</span>
    </div>
    <style>
      :root>*{border:1px red solid;}
    </style>
</my-element>

I hoped, the :root-Selector would do the job inside of a shadow dom, but thats not the case.

It would also be a possible solution if someone shows how to set an ID on the shadow root.

Update:

Tried using #shadow-root > * as selector:

seems not to work. Probably it is just google chrome developer tools visualizing the shadow root element like that.

like image 697
Michael K Avatar asked Mar 06 '17 14:03

Michael K


People also ask

Which selector can work for shadow DOM elements?

There's no selector that can directly affect shadow DOM styles from the document. But just as we expose methods to interact with our component, we can expose CSS variables (custom CSS properties) to style it.

How do you inspect shadow roots?

Find the shadow root element: Check the shadow root's parent tag and get it using javascript. In this case, the shadow host tag is the div element <div id=”shadow_host"> . The executeScript() function will retrieve the shadow root. This code above works in both Selenium 3 and 4.

How do I access shadow DOM elements?

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.

How do you add a shadow element in CSS?

In CSS, shadows on the boxes of elements are created using the box-shadow property (if you want to add a shadow to the text itself, you need text-shadow ). The box-shadow property takes a number of values: The offset on the x-axis. The offset on the y-axis.


1 Answers

Use this selector: :host > *

The :host selector is described in https://drafts.csswg.org/css-scoping/#host-selector

document.querySelector( 'my-element' )
  .attachShadow( { mode: 'open' } )
  .innerHTML = `
    <span>SPAN</span>
    <a>A</a>
    <p>P</p>
    <div>
      DIV
      <span>SPAN IN DIV</span>
    </div>
    <style>
      :host>*{border:1px red solid;}
    </style>`
<my-element>
</my-element>

:host may also hold a compound selector, which must be places in brackets. E.g. :host([foo=bar]) selects a host element which has attribute foo set to bar.

like image 117
Supersharp Avatar answered Sep 22 '22 19:09

Supersharp