<button id="addDiv">Add Div</button>
<div id="container">
<input id="checkbox" type="checkbox">
<p>Inputs Listed Below</p>
</div>
input {
margin: 0 0 1rem 0;
}
label {
margin: 0 0 0 1rem;
}
#checkbox {
display: block;
margin: 1rem;
}
(function (d) {
"use strict";
const container = d.querySelector("#container");
var i = 0;
d.querySelector("#addDiv").addEventListener("click", addDiv);
function addDiv() {
var w = d.createElement("DIV");
var z = d.createElement("INPUT");
var z2 = d.createElement("Label");
var labelContent = d.createTextNode("Label " + i);
z.setAttribute("type", "text");
w.id = "myDiv" + i;
z.id = "textDescription" + i;
z2.setAttribute("for", z.id);
z2.id = "myLabelId" + i;
// lets add a class so we make them easier to find
z2.className = "z2Class";
z2.appendChild(labelContent);
i++;
w.append(z);
w.append(z2);
d.getElementById("container").appendChild(w);
}
// bind click handler to element that is added later/dynamically
container.addEventListener("click", function (e) {
// If the event target doesn't match bail
if (!event.target.classList.contains("z2Class")) return;
// Now do something
console.log("My Function Runs ");
if (document.getElementById("checkbox").checked) {
//would be better to add a class for css to use instead of this
event.target.style.color = "blue";
} else {
//would be better to add a class for css to use instead of this
event.target.style.color = "red";
}
});
})(document);
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.