You can create a div element containing an input and a label for each element of the array. Each one of these elements needs to be appended to an existing parent element option. You can achieve this by writing down the actual HTML inside back-quotes. Then create an empty element with document.createElement. Using the innerHTML property you can fill this element with the HTML you wrote. Finally append it like you did using appendChild:
const html = `
<div>
<input type="checkbox" id="${name}" name="${name}">
<label for="${name}">${name}</label>
</div>
`.trim();
const wrapper = document.createElement('div');
wrapper.innerHTML = html;
const element = option.appendChild(wrapper.firstChild);
Instead of using forEach to loop through your array, I would use map which allows us to create an array of input elements on the go. It's the exact same as using a forEach... the only difference is you need to return an element in your callback function:
const checkboxes = names.map(function(name) {
const html = `
<div>
<input type="checkbox" id="${name}" name="${name}">
<label for="${name}">${name}</label>
</div>
`.trim();
const wrapper = document.createElement('div');
wrapper.innerHTML = html;
const element = option.appendChild(wrapper.firstChild);
return element.querySelector('input');
});
So now we have an array called checkboxes which holds four input elements corresponding to our four names contained in the initial names array.
Whenever you need to know the checkboxes that are checked you can filter them out and get the names of the remaining ones. We'll do this using filter and another map:
checkboxes.filter(checkbox => checkbox.checked)
.map(checkbox => checkbox.name);
Here's the full code:
const option = document.querySelector('.option');
const names = ['Joe', 'Mike', 'Sara', 'Jack'];
const checkboxes = names.map(function(name) {
const html = `
<div>
<input type="checkbox" id="${name}" name="${name}">
<label for="${name}">${name}</label>
</div>
`.trim();
const wrapper = document.createElement('div');
wrapper.innerHTML = html;
const element = option.appendChild(wrapper.firstChild);
return element.querySelector('input');
});
setTimeout(function() {
const selected = checkboxes.filter(checkbox => checkbox.checked);
console.log(selected.map(checkbox => checkbox.name));
}, 3000)
<div class="option">
</div>