Shadow Dom in HTML

–HTML

<template id="listener">
<style>
     .head{
          font-size: 25px;
          font-weight: bold;
     }
</style>
<div class="head">This is shadow DOM text</div>
</template>

<div class="head">This is normal text</div>
<div id="host"></div>

–JS

var host = document.querySelector('#host');
var shadowRoot = host.createShadowRoot();
var listener = document.querySelector('#listener');
var clone = document.importNode(listener.content, true);
shadowRoot.appendChild(clone);

OR

It’s Kind of shadow that will different between effecting CSS to HTML separately.

In Angular we can active it with ViewEncapsulation.Native

Why we use it ?

Because if we can have same name class with more than one div this will allow to all. But with shadow Dom it won’t be.

–HTML

<div class="has">Without Shadow DOM</div>

<div id="hasDOM">There is DOM !</div>

–CSS

.has{
  color:blue
}

–JS

var host = document.querySelector('#hasDOM');
var shadowRoot = host.createShadowRoot();
var div = document.createElement('div');
div.textContent = "This is text with Shadow DOM";
div.className = "has";

shadowRoot.appendChild(div);

–Live Demo

[codepen_embed height=”265″ theme_id=”0″ slug_hash=”GXdrEr” default_tab=”js,result” user=”pradeepanvi”]See the Pen Shadow DOM by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]

Leave a Reply

Your email address will not be published. Required fields are marked *