Javascript DOM HTML OptionGroup Object create

Introduction

We can create an <optgroup> element via the document.createElement() method:

var x = document.createElement("OPTGROUP");

Click the button to create an OPTGROUP element.

View in separate window

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Test</button>

<select id="mySelect" size="6">
  <option>CSS</option>
  <option>HTML</option>
  <option>SQL</option>
  <option>Javascript</option>
  <option>C++</option>
</select>/*from w ww  .  j  a  v a  2  s. c o  m*/

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

</body>
</html>



PreviousNext

Related