Create an OptionGroup Element - Javascript DOM HTML Element

Javascript examples for DOM HTML Element:OptionGroup

Introduction

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

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">create an OPTGROUP element</button>

<select id="mySelect" size="6">
  <option>CSS
  <option>HTML
  <option>SQL
  <option>Java
  <option>Javascript
</select>/*w w w.ja v a2  s.  c  o m*/

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

</body>
</html>

Related Tutorials