Al Ameen
Al Ameen

Reputation: 372

How to change css of an element in shadow Dom when the main dom contains a class

This is the code:

<html>
  <div class="parent-div">
    <div id="shadow_host">
      #shadow-root(open)          
    <div class="child-div">some random things</div>
    </div>
  </div>      
</html>

I have append a shadow dom to an element. I want to change the css of the element with the class child-div when ever the main dom has a parent element with class parent-div. Is it possible to do from css like

.parent-div .child-div{
   display:none
}

Upvotes: 8

Views: 9851

Answers (3)

Bartho Bernsmann
Bartho Bernsmann

Reputation: 2503

#shadow_host::part(native) {
  color: black;
  border: dashed 2px black;
  background-color: #fec0ff;
}

#shadow_host::part(button):hover {
  background-color: #fd8fff;
}

Upvotes: 1

Supersharp
Supersharp

Reputation: 31181

You can use :host-context() CSS fonction in the Shadow DOM style.

:host-context(.parent-div) .child-div{
   display:none
}

document.querySelector( '#shadow_host' )
    .attachShadow( { mode: 'open' } )
    .innerHTML = `
        <style>
            :host-context(.parent-div) .child-div {
                display:none
            }
        </style>
        <div class="child-div">some random things</div>
    `
<div class="parent-div">
  <div id="shadow_host">
   </div>
</div>      

Upvotes: 2

JensW
JensW

Reputation: 442

You can use the ::shadow selector to style elements in the Shadow DOM.

You can also add a <style> tag to the shadow DOM using javascript's .innerHTML function and style it that way.

Upvotes: 1

Related Questions