JSFiddle - React, Tailwind, and code Playground

HTML

<p>The groups below are constructed slightly differently, but should have the exact same functionality: when a radio button is clicked, the group should send an alert to the browser. The difference in construction is that the clickable labels in Group 1 are wrapped around the radio buttons to make them clickable. The radio buttons in Group 2 are separate elements making use of the "for" attribute to point to the correct radio buttons. Every button is given an event listener for "change". Only the buttons in Group 2 respond to the change properly.</p><br />
<div id="group1"></div>
<br />
<div id="group2"></div>

JavaScript

var g1 = document.getElementById("group1");
var g2 = document.getElementById("group2");

//Populating group 1
document.getElementById("group1").innerHTML += "Group 1 (Doesn't work)<br />";
for (var i = 0; i < 3; i++)
{
    var label = document.createElement("label");
    var radio = document.createElement("input");
    radio.setAttribute("type", "radio");
    radio.setAttribute("name", "group1");
    
    radio.addEventListener("change", function()
                           {
                               alert("group1 changed!")
                           }, false);
    
    label.appendChild(radio);
    label.appendChild(document.createTextNode("Radio " + (i + 1)));
    var br = document.createElement("br");
    g1.appendChild(label);
    g1.appendChild(br);
}

// Populating group 2
document.getElementById("group2").innerHTML += "Group 2 (Works)<br />";
for (var i = 0; i < 3; i++)
{
    var radio = document.createElement("input");
    radio.setAttribute("type", "radio");
    radio.setAttribute("name", "group2");
    radio.setAttribute("id", "g2r" + i);
    
    radio.addEventListener("change", function()
                           {
                               alert("group2 changed!")
                           }, false);
    
    var label = document.createElement("label");
    label.setAttribute("for", "g2r" + i);
    label.innerHTML = "Radio " + (i + 1);
    var br = document.createElement("br");
    g2.appendChild(radio);
    g2.appendChild(label);
    g2.appendChild(br);
}