'Dynamically setting options for a select elements skips first element

I've dynamically built an options array divided in two options group. These options groups are stored in a javascript array named ogs. The code for the same is as below:

var ogs = [];
for (optGroup in optionsList) {
    var og = document.createElement('optgroup');
    og.label = optGroup;
    var ops = optionsList[optGroup];
    for (op in ops) {
        var o = document.createElement('option');
        o.value = op;
        o.text = ops[op];
        og.appendChild(o);
    }
    ogs.push(og);
}

Now, I'm trying to add these options to 2 select elements, as below:

var from_el = document.getElementById('from_selector'), to_el = document.getElementById('to_selector');
for (i = 0; i < ogs.length; ++i) {
    var og = ogs[i];
    from_el.add(og);
    to_el.add(og);
}

However, at the end of the script, only to_selector has the options populated, whereas from_selector remains empty. The reason I'm populating the options like this is because both these select elements use select2, and any other method (such as innerHTML) is taking significantly longer. I've also tried putting these selectors in array and iterating over them, always the last select gets populated, whereas first select remains empty.



Solution 1:[1]

Figured out the issue. The problem was in the following lines:

from_el.add(og);
to_el.add(og);

When og was getting added to to_el, it was getting detached from from_el. The solution was to replace this with.

from_el.add(og);
to_el.add(og.cloneNode(true));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gaurav