Q_24500437: How to add an optgroup cross-browser

This example shows how to add an optgroup element dynamically cross-browser to a dynamically created selection list

This page will remain online for future reference. The original question can be viewed at Experts-Exchange, but requires (free) membership. More information about me, about how this site is maintained and about how to use these pages for yourself, check out the opening page.

Use the following code:

function addOptGroup(){
    var select = document.getElementById("testselect");
    var optgroup = document.createElement("optgroup");
    optgroup.label = "new optgroup";
    select.appendChild(optgroup);
    var option = new Option("the value sent");
    option.innerHTML = "what you see";
    optgroup.appendChild(option);
}
	

You can test the above code by clicking the button, it will call the function addOptGroup and add an optgroup and an option to the select list