Hopefully I’m not going to cause offense here, but I do find this confusing. What is ‘w’, what is ‘z’, what is ‘z2’? Personally I would go with more descriptive names.
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);
}
I think a better and less cumbersome alternative here is to go with a template string
My html isn’t quite the same, a mix of the above really, but should illustrate my point. You could go with this instead
const rowTemplate = function(count) {
return `
<div id='row-${count}' class='row'>
<div>
<label for='textDescription-${count}'>
<input type='text' id='textDescription-${count}'>
</div>
<div>
<button id="btn-${count}" data-for='textDescription-${count}'>Click me</button>
</div>
</div>
`
}
Note I have mimicked the label’s for by adding a dataset for property to the button e.g. data-for='textDescription-${count}'
.
So no need to slice numbers we can access the textbox in the handler with
parent.querySelector(`#${target.dataset.for}`)
Another example of using a function to return a template. Here I am passing in an object with an id and an array. Dynamically I am then able to build a list using Array.map
const namesTemplate = ({id, names = []}) => (
`
<ul id='${id}'>
${names.map(name => `<li>Name is ${name}</li>`).join('\n\t')}
</ul>
`
)
console.log(
namesTemplate({
id: 'names-01',
names: ['Rod', 'Jane', 'Freddy']
})
)
//Output
/*
<ul id='names-01'>
<li>Name is Rod</li>
<li>Name is Jane</li>
<li>Name is Freddy</li>
</ul>
*/
There are apparently security risks with this approach if the arguments to the template come form an outside source such as user input. That said there are methods to sanitize the html (DOMPurify seems to come highly recommended)
Anyway here is a codepen. I’m sure it doesn’t fit your brief exactly, but hopefully it is of use.