<button id="addDiv">Add Div</button>
<div id="container">
</div>
input {
margin: 0 0 1rem 0;
}
label {
margin: 0 0 0 1rem;
}
#checkbox {
display: block;
margin: 1rem;
}
label.highlight {
background: red;
}
input.highlight {
border-color: red;
outline: 0;
}
(function (d) {
"use strict";
const container = d.querySelector("#container");
const myDiv = "myDiv";
const textDescription = "textDescription";
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("Click Me " + 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) {
var index = e.target.id.slice(-1); // find last digit
var theInput = d.querySelector("#" + textDescription + index);
// If the event target doesn't match bail
if (!event.target.classList.contains("z2Class")) return;
// Now do something
theInput.classList.add("highlight");
e.target.classList.add("highlight");
});
})(document);
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.