user1734698
user1734698

Reputation: 167

Appending a button to an existing shadowroot element is not correct

var shadow = document.getElementById(
        "3rd-party-div"
      ).shadowRoot; 
      
let style = document.createElement("style");
      style.textContent = `
      .custom_button{
    
    padding: 10px;
    display:block;
    float:left;
    text-align:center;
}
`
shadow.appendChild(style);
let customButton = document.createElement("button");
customButton.setAttribute("class", "custom_button");
customButton.innerHTML = "Back to Overview";
      
      

I have a shadowRoot in my HTML page which I am accessing via this piece of code

var shadow = document.getElementById(
        "3rd-party-div"
      ).shadowRoot; 

Now I want to create a button and attach it to this shadowroot. Below code -

      let customButton = document.createElement("button");
      customButton.setAttribute("class", "custom_button");
      customButton.innerHTML = "Back to Overview";

And I append this button to shadow element with this code shadow.appendChild(customButton); I have my css styling which I also append to the shadowroot.

Now my button is coming in the page, but it below my shadowroot div. Is there anyway to keep it as part of my shadow div itself?

Upvotes: 2

Views: 3292

Answers (1)

MiKo
MiKo

Reputation: 2146

I'm not sure I quite understand what you want to achieve, but based on your recent comment I think you want to keep the content of your div, attach a shadow DOM to it and add a button to the same div.

Attaching a shadow will replace the original DOM subtree of the host. If you want to preserve it, you can use a <slot>.

const thirdPartyDiv = document.getElementById("3rd-party-div");

// Button inside the 3rd-party-div
const customButtonExt = document.createElement("button");
customButtonExt.innerHTML = "Back to Overview (inside 3rd party div)";
thirdPartyDiv.appendChild(customButtonExt);

// Attach shadow and keep the content of the div by using a <slot>
thirdPartyDiv.attachShadow({ mode: "open" }).innerHTML = '<slot></slot>';
      
const shadow = thirdPartyDiv.shadowRoot; 
      
const style = document.createElement("style");
style.textContent = `
  .custom_button {
    padding: 10px;
    display:block;
    float:left;
    text-align:center;
}
`;
shadow.appendChild(style);

// Button inside the shadow
const customButton = document.createElement("button");
customButton.setAttribute("class", "custom_button");
customButton.innerHTML = "Back to Overview (inside shadow)";

shadow.appendChild(customButton);
<div id="3rd-party-div">
  <div>Content of the 3rd-party div!</div>
</div>

Upvotes: 4

Related Questions