Q:

Can't get the selected group?

 <select class="" id="buyCountriesSel"></select>

load it with :
  $('#buyCountriesSel').append($('<optgroup id="abc" label="USA">'));
    for (var key in statesCodesUS)  $('#buyCountriesSel').append($('<option></option>').val(key).text(statesCodesUS[key]) );
    $('#buyCountriesSel').append($('</optgroup>'));

read it with :
   $('#buyCountriesSel').on('change', function() {
     var selected = $( "#buyCountriesSel option:selected" );
       var area = selected.closest('optgroup').attr("id"); // .parent() also not work
       alert(area);
   });

Expected to get USA. This will give me the buyCountriesSel object, and not the group with label="USA"
Using parent() instead of closest also not working, trying to check .label will also produce undefined.

A:

append() doesn't concatenate HTML fragments, it creates DOM elements. You need to append the options to the optgroup, not the select.

var usa_group = $('<optgroup id="abc" label="USA">');
for (var key in statesCodesUS) {
  usa_group.append($('<option></option>', {
    value: key,
    text: statesCodesUS[key]
  }));
}
$('#buyCountriesSel').append(usa_group);
<select class="" id="buyCountriesSel"></select>

