I have two empty select fields, I want to iterate once over some array, create an option element in each iteration, and append it to both select fields. The problem is that only the last element gets the options, the first one remains empty:
HTML
<select class="form-control" id="typeCol">
</select>
<br>
<select class="form-control" id="diffCol">
</select>
JavaScript
let typeCol = document.getElementById('typeCol');
let diffCol = document.getElementById('diffCol');
for (let i in cols) {
let opt = document.createElement('option');
opt.value = i;
opt.innerHTML = cols[i];
typeCol.appendChild(opt);
diffCol.appendChild(opt);
}
Adding another for loop and appending to the second select from there seems to work, but still - what's going on?
An element can only be inside one parent. If you use appendChild on an element that already has a parent, it's moved from the old parent to the new one.
You can use cloneNode to create a clone of the element instead:
diffCol.appendChild(opt.cloneNode(true));
Example:
let typeCol = document.getElementById('typeCol');
let diffCol = document.getElementById('diffCol');
let cols = ["one", "two", "three"];
for (let i in cols) {
let opt = document.createElement('option');
opt.value = i;
opt.innerHTML = cols[i];
typeCol.appendChild(opt);
diffCol.appendChild(opt.cloneNode(true));
}
<select class="form-control" id="typeCol">
</select>
<br>
<select class="form-control" id="diffCol">
</select>
You can't append same element, However you can use cloneNode() method to create a clone then append it.
typeCol.appendChild(opt);
diffCol.appendChild(opt.cloneNode(true));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With