Javascript Reference - HTML DOM Option Object








The Option object represents an HTML <option> element.

Option Object Properties

Property Description
defaultSelected Get the default value of the selected attribute
disabled Disable or enable an option
form Get the form that contains the option
index Sets or gets the index position of an option in the select element
label Sets or gets the label attribute of an option in a drop-down list
selected Sets or gets the selected state of an option
text Sets or gets the text of an option
value Sets or gets the value of an option




Standard Properties and Events

The Option object supports the standard properties and events.

Example

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


<!DOCTYPE html>
<html>
<body>
<select>
  <option id="myOption" value="A">A</option>
  <option value="B">B</option>
</select><!--from  ww  w  .  ja v  a  2 s .co  m-->
<button onclick="myFunction()">test</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementById("myOption").text;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

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


<!DOCTYPE html>
<html>
<body>
<!-- w ww  . ja  v  a 2s .com-->
<select id="mySelect">
</select>
<button onclick="myFunction()">test</button>
<p id="demo"></p>

<script>
function myFunction() {
    var x = document.createElement("OPTION");
    x.setAttribute("value", "A");
    var t = document.createTextNode("A");
    x.appendChild(t);
    document.getElementById("mySelect").appendChild(x);
}
</script>

</body>
</html>

The code above is rendered as follows: