corysimmons
corysimmons

Reputation: 7695

Select Shadow DOM with JavaScript and/or CSS?

It seems like Chrome deprecated /deep/ and >>> and ::shadow: https://www.chromestatus.com/features/6750456638341120

Does anyone know if there is another way to access the Shadow DOM?

My use case is trying to figure out the style of an input. Specifically I'm trying to detect if a placeholder is being displayed or not.

I've tried el.shadowRoot but it returns null and the docs for it are pretty sparse.

Upvotes: 3

Views: 4459

Answers (2)

Supersharp
Supersharp

Reputation: 31219

You can only access Shadow DOM of the elements created via a call to attachShadow( { mode: 'open' } ). If it is the case then calling shadowRoot should work.

You cannot access Shadow DOM from user agent controls (<input>, <select>), added by the browser.

To check if a placeholder is displayed or not, I would verify if it exists and if the input value is empty or not:

if ( myInput.getAttribute( "placeholder" ) && !myInput.value.length )
    //the placeholder is being displayed

myInput.oninput = function() {
  if (myInput.getAttribute("placeholder") && !myInput.value.length)
    myInput.classList.add("empty")
  else
    myInput.classList.remove("empty")
}
 body {
   padding: 100px;
 }
 input {
   border: 2px solid;
   padding: 10px;
   outline: none;
 }
 input:valid {
   border-color: springgreen;
 }
 input:invalid {
   border-color: tomato;
 }
 input[placeholder].empty {
   border-color: darkturquoise
 }
<input type="text" required placeholder="the placeholder" id="myInput" class="empty">

Update

Chrome and Safari support the CSS pseudo-class :placeholder-shown that can be used to style your element when the placeholder is displayed.

Upvotes: 4

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658077

If you use shady DOM (default) instead of shadow DOM, then you need to use Polymer API to access the DOM.

Polymer.dom(el.root)

AFAIK it's not decided yet if >>> and ::shadow will be removed from JS. Therefore querySelector('x >>> y') might be supported longer. For CSS it's definitive that it will be removed.

Upvotes: 1

Related Questions