Rushabh Shah
Rushabh Shah

Reputation: 171

shadow DOM not showing content. How to make content visible in DOM?

As you can see I want to add content dynamically but shadow DOM is not showing content How can I make content visible? I want to make content visible.

let shadow = document.querySelector('#nameTag').createShadowRoot();
let content_area =  document.querySelector("#nameTag");
content_area.innerHTML = '<p>Hello world!</p>';
let template = document.querySelector('#nameTagTemplate');
shadow.appendChild( template.content.cloneNode(true) );
shadow.appendChild( template.content );
h2{
    color: red;
    font-size: 24px;
    font-weight: bold;
}
<h2>Hello world!</h2>
<div id="nameTag"></div>
<template id="nameTagTemplate">
    <div class="outer">
        <div class="name"></div>
    </div>
</template>

Upvotes: 4

Views: 6247

Answers (1)

Intervalia
Intervalia

Reputation: 10945

First you should be using the V1 function attachShadow instead of the V0 function createShadowRoot. The V0 spec is deprecated and will not be supported in most browsers and will be removed from Chrome soon.

Second, you need a <slot> in your template into which the children of <div id="nameTag"></div> will show.

Third you were appending both a clone of the template and the original template into the shadowRoot. Not sure you wanted to do that so I took it out in my example.

let shadow = document.querySelector('#nameTag').attachShadow({mode:'open'});

let content_area =  document.querySelector("#nameTag");
content_area.innerHTML = 'I show in the slot';

let template = document.querySelector('#nameTagTemplate');
shadow.appendChild( template.content.cloneNode(true) );
h2{
    color: red;
    font-size: 24px;
    font-weight: bold;
}

#nameTag {
  border: 1px dashed blue;
}
<h2>Hello world!</h2>
<div id="nameTag"></div>
<template id="nameTagTemplate">
    <div class="outer">
        <div class="name"><slot></slot></div>
    </div>
</template>

Upvotes: 2

Related Questions