Question

I have this example:

http://codepen.io/dbugger/pen/IuDxw

Where I have an insertion point inside the Shadow DOM and I try to apply an style to it, making it disappear. But the image is still visible. I suspect there is some principle I haven't undestood propely from the Web Components.

Can someone explain me what am I doing wrong?

Was it helpful?

Solution

The trick is that the image is not, as kkemple mentioned, part of the Shadow DOM, but rather the Light DOM, which means it's not directly accessible from inside the component. It's user provided content, like the parameters passed into a class constructor in an OOP language. If at all possible, then, the user should provide their own styles to go with it.

That being said, there are definitely valid use cases where the component author wants to style user-provided content. Hiding certain parts of the user-provided markup based on attributes on the host, events (clicks), etc. is definitely one of those. In that case, wrap the <content> element in a Shadow DOM element and hide that:

<template>
  <style>
    .image {
      display: none;
    }
  </style>
  <div class="image">
    <content></content>
  </div>
</template>

http://codepen.io/anon/pen/rCGqD

On a side note: It is technically possible to apply styles directly to Light DOM elements, but be aware that in many cases this is considered leaking implementation details to the outside world. If the first solution works, use that instead.

OTHER TIPS

Not sure why you got a down vote for this but the reason it is not working is because your code is not in the shadow DOM, the div and image is still accessible through default styling. I forked your codepen and added the styling so you could see.

http://codepen.io/kkemple/pen/euBKs

I didn't go in to why it was not creating a shadow DOM element as your JS looked correct to me but here is a great article on shadow DOM web-ponents:

http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top