Cannot add option to multiple optgroup

Viewed 38

I'm trying to add an option to multiple optgroup, the problem is that this option is only displayed on a single optgroup, I don't know if this mechanism is the default logic of the html or I did an error:

$(document).ready(function() {
      $('#options').append('<optgroup label="category1"></optgroup>');
      $('#options').append('<optgroup label="category2"></optgroup>');
    
      var opt1 = new Option("test1", 1);
      var opt2 = new Option("test2", 2);
    
      $('#options optgroup[label=category1]').append(opt1);
      $('#options optgroup[label=category2]').append(opt1);
      $('#options optgroup[label=category1]').append(opt2);
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<select id="options">
</select>

result:

enter image description here

as you can see the option test1 is associated to 2 categories, but is only displayed on a single category.

This is a fiddle.

1 Answers

This happens because opt1 reference same DOM. Append sencond time just change dom place. You can't have an element in two different places.

You can create new DOM object or clone it

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<select id="options">
</select>

$(document).ready(function() {
      $('#options').append('<optgroup label="category1"></optgroup>');
      $('#options').append('<optgroup label="category2"></optgroup>');
    
      var opt1 = new Option("test1", 1);
      var opt2 = new Option("test2", 2);
    
      
      $('#options optgroup[label=category1]').append(opt1);
      $('#options optgroup[label=category2]').append($(opt1).clone());
      $('#options optgroup[label=category1]').append(opt2);
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<select id="options">
</select>

Related