Here's an example:
http://www.spookandpuff.com/examples/optGroup.html
And here's the function - which is adapted from your original one:
function addOption(selectbox, contents, cl )
{
var addNode = selectbox; //Cache the selectbox, in case we're only adding a single, ungrouped, option.
if (contents.length > 1) { //If we're adding a group
addNode = document.createElement("OPTGROUP"); //Set the node to add to to a new optgroup.
addNode.label = contents[0]; //Use the first label (a string) as the group's label.
contents.shift(); //Remove the label from the array (so it doesn't get re-used)
}
for (var i=0;i < contents.length;i++) {
var optn = document.createElement("OPTION");
optn.text = contents[i][0];
optn.value = contents[i][1];
if (cl==1){ optn.className = "nav_option_main"; }
addNode.appendChild(optn); //Append this option to either the selectbox, or the group.
}
if (contents.length > 1) { //If we've just added a group, we need to add the group to the select box.
selectbox.appendChild(addNode);
}
}
This version accepts a parameter 'contents', rather than a separate params for 'text' and 'value' - this accepts an array of one or more options. So, to add a single option, not as part of a group, do this:
var singleOption = [
['singleOption', 1]
];
addOption(document.getElementById('selector'), singleOption, 0);
The item in the contents array is itself an array of two items - the text, and the value.
If you stack more than one of these into the contents array, you create an optGroup:
var optionGroup1 = [
'Group Title',
['groupOne.one', 1],
['groupOne.two', 2],
['groupOne.three', 3],
['groupOne.four', 4],
['groupOne.five', 5]
];
addOption(document.getElementById('selector'), optionGroup1, 0);
The first item is the title for the group, after that, it's just repeating the same content as the single item. When the function detects you're trying to add more than one at a time, it groups them together.
Is that what you're after?