HTML DOM Select selectedIndex Property


The HTML DOM select selectedIndex property returns and modify the index of selected option of the drop-down list in an HTML document.

Syntax

Following is the syntax −

1. Returning selectedIndex

object.selectedIndex

2. Modifying selectedIndex

object.selectedIndex = “number”

Example

Let us see an example of HTML DOM select selectedIndex property −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
   html{
      height:100%;
   }
   body{
      text-align:center;
      color:#fff;
      background: radial-gradient( circle farthest-corner at 23.1% 64.6%, rgba(129,125,254,1) 0%, rgba(111,167,254,1) 90% ) no-repeat;
      height:100%;
   }
   p{
      font-weight:700;
      font-size:1.1rem;
   }
   .drop-down{
      display:block;
      width:35%;
      border:2px solid #fff;
      font-weight:bold;
      padding:2px;
      margin:1rem auto;
      outline:none;
   }
   .btn{
      background:orange;
      border:none;
      height:2rem;
      border-radius:2px;
      width:35%;
      margin:2rem auto;
      display:block;
      color:#fff;
      font-weight:bold;
      outline:none;
      cursor:pointer;
   }
   .show{
      font-size:1.5rem;
      font-weight:bold;
   }
</style>
</head>
<body>
<h1>DOM Select selectedIndex property Demo</h1>
<p>Hi, Select your favourite subject:</p>
<select class='drop-down' name="Drop Down List">
<option>Physics</option>
<option>Maths</option>
<option>Chemistry</option>
<option>English</option>
<option>Economics</option>
<option>Hindi</option>
<option>Biology</option>
</select>
<button type="button" onclick="set()" class="btn">Set selectedIndex</button>
<div class="show"></div>
<script>
   function set() {
      var dropDown = document.querySelector(".drop-down");
      document.querySelector(".show").innerHTML="put selectedIndex = '3'";
      dropDown.selectedIndex="3";
   }
</script>
</body>
</html>

Output

This will produce the following output −

Click on “Set selectedIndex” button to set selectedIndex=’3’ on the drop-drown list.

raja
Published on 19-Jul-2019 12:17:30
Advertisements