Javascript Reference - HTML DOM OptionGroup Object








The OptionGroup object represents an HTML <optgroup> element.

OptionGroup Object Properties

Property Description
disabled Endable or disable an option-group
label Sets or gets the label attribute of an option-group

Standard Properties and Events

The OptionGroup object supports the standard properties and events.

Example

We can access an <optgroup> element by using getElementById().


<!DOCTYPE html>
<html>
<body>
<!--from  w  w  w.ja  v  a 2  s  .  c  om-->
<select size="4">
  <optgroup id="myOptgroup" label="My Group">
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
  </optgroup>
</select>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {
    var x = document.getElementById("myOptgroup").label;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

We can create an <optgroup> element by using the document.createElement() method.


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<!--from  w w  w  . ja  v a2  s . co m-->
<select id="mySelect" size="6">
  <option>A
  <option>B
  <option>C
  <option>D
  <option>E
</select>

<script>
function myFunction() {
    var x = document.getElementById("mySelect");
    var y = document.createElement("OPTGROUP");
    y.setAttribute("label", "SwedishCars");
    y.appendChild(x.options[3])
    x.insertBefore(y, x.options[3]);
}
</script>

</body>
</html>

The code above is rendered as follows: