Jonny B
Jonny B

Reputation: 720

Shadow DOM: Elements attached to shadow DOM not rendering

I'm trying to understand how radio buttons work within a shadow dom. I have a script tag where I'm attaching a shadow DOM to an element and then appending some radio buttons. My problem is that the radio buttons are not rendering.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>Radio Buttons:</p>
<div id="containter">

</div>

<script>
    let shadowContainer = document.getElementById('containter');
    shadowContainer.attachShadow({mode: 'open'});

    let input1 = document.createElement('input');
    input1.setAttribute("type", "radio");
    input1.setAttribute("id", "1");
    input1.setAttribute("name", "group");
    input1.setAttribute("value", "1");

    let input2 = document.createElement('input');
    input2.setAttribute("type", "radio");
    input2.setAttribute("id", "2");
    input2.setAttribute("name", "group");
    input2.setAttribute("value", "2");

    let input3 = document.createElement('input');
    input3.setAttribute("type", "radio");
    input3.setAttribute("id", "3");
    input3.setAttribute("name", "group");
    input3.setAttribute("value", "3");

    shadowContainer.appendChild(input1);
    shadowContainer.appendChild(input2);
    shadowContainer.appendChild(input3);
</script>
</body>
</html>

Upvotes: 0

Views: 2856

Answers (1)

Adam H
Adam H

Reputation: 1818

The problem is you aren't adding the elements to the shadowDom, you are adding them to the div. Simply store the return value from .attachShadow and append to that. Here is your example doing just that.

let shadowContainer = document.getElementById('containter');
// store the reference
let container = shadowContainer.attachShadow({
  mode: 'open'
});

let input1 = document.createElement('input');
input1.setAttribute("type", "radio");
input1.setAttribute("id", "1");
input1.setAttribute("name", "group");
input1.setAttribute("value", "1");

let input2 = document.createElement('input');
input2.setAttribute("type", "radio");
input2.setAttribute("id", "2");
input2.setAttribute("name", "group");
input2.setAttribute("value", "2");

let input3 = document.createElement('input');
input3.setAttribute("type", "radio");
input3.setAttribute("id", "3");
input3.setAttribute("name", "group");
input3.setAttribute("value", "3");

// append to the reference 
container.appendChild(input1);
container.appendChild(input2);
container.appendChild(input3);
<p>Radio Buttons:</p>
<div id="containter">

</div>

Upvotes: 4

Related Questions