Option Object
The Option object represents an HTML <option> element.
Access an Option Object
You can access an <option> element by using getElementById():
Example(1)
<select> <option id="myOption" value="volvocar">Volvo</option> <option value="saabcar">Saab</option> </select> <button onclick="get_option()">Try it</button> <p id="demo"></p> <script> function get_option() { var x = document.getElementById("myOption").text; document.getElementById("demo").innerHTML = x; } </script>
In above example when you click button it will get the text of the Volvo option in the drop-down list.
<select id="mySelect"></select> <button onclick="add_option()">Try it</button> <h2 id="demo"></h2> <script> function add_option() { var x = document.createElement("OPTION"); x.setAttribute("value", "volvocar"); var t = document.createTextNode("Volvo"); x.appendChild(t); document.getElementById("mySelect").appendChild(x); } </script>
<!DOCTYPE html> <html> <head> <title>How To Use HTML DOM Options Object With JavaScript</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <body> <div class="container"> <br> <div class="text-center"> <h1 id="color" style="color: tomato">How To Use HTML DOM Options Object With JavaScript</h1> </div> <div class="col-md-2"></div> <div class="col-md-8"> <div class="well"> <select class="form-control"> <option id="myOption" value="volvocar">Volvo</option> <option value="saabcar">Saab</option> </select><br><br> <button class="btn btn-success" onclick="get_list()">Click it</button> <h2 id="demo"></h2> <select id="mySelect" class="form-control"> </select><br><br> <button class="btn btn-success" onclick="add_option()">Add</button> <h2 id="demo"></h2> </div> </div> <div class="col-md-2"></div> <script> function get_list() { var x = document.getElementById("myOption").text; document.getElementById("demo").innerHTML = x; } function add_option() { var x = document.createElement("OPTION"); x.setAttribute("value", "volvocar"); var t = document.createTextNode("Volvo"); x.appendChild(t); document.getElementById("mySelect").appendChild(x); } </script> </div> </body> </html>