Javascript Reference - HTML DOM Option index Property








The index property sets or gets the index position of an option in a drop-down list.

The index starts at 0.

Browser Support

index Yes Yes Yes Yes Yes

Syntax

Return the index property.

var v = optionObject.index

Set the index property.

optionObject.index=integer

Property Values

Value Description
integer Set the index position of the option within a drop-down list




Return Value

A Number type value representing the index position of the option within a drop-down list. The index starts at 0.

Example

The following code shows how to get the text and index of all options in a drop-down list.


<!DOCTYPE html>
<html>
<body>
<!--from w w w. j av  a  2 s  . c o  m-->
Select your favorite fruit:
<select id="mySelect">
  <option>A</option>
  <option>B</option>
  <option>C</option>
  <option>D</option>
</select>
<button type="button" onclick="myFunction()">test</button>

<script>
function myFunction() {
    var x = document.getElementById("mySelect");
    var i;
    for (i = 0; i < x.length; i++) {
        console.log(x.options[i].text + " has index: " + x.options[i].index);
    }
}
</script>

</body>
</html>

The code above is rendered as follows: