Javascript Reference - HTML DOM Option label Property








The label property sets or gets the label attribute in an option in a drop-down list.

Browser Support

The label property is supported in all major browsers.

label Yes Yes Yes Yes Yes

Syntax

Return the label property.

var v = optionObject.label 

Set the label property.

optionObject.label=text

Property Values

Value Description
text Set the label for the option




Return Value

A String type value representing the label of the option in the drop-down list.

Example

The following code shows how to change the label value of an option in a drop-down list.


<!DOCTYPE html>
<html>
<body>
<!--   ww  w.j a  va2 s .  c om-->
<select>
  <option label="A">A</option>
  <option id="myOption" label="B">B</option>
</select>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
    document.getElementById("myOption").label = "newLabel";
}
</script>
</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to get the label value of an option in a drop-down list.


<!DOCTYPE html>
<html>
<body>
<!--from www . j a v  a2  s.  co  m-->
<select size="2">
  <option id="myOption" label="B">B</option>
  <option label="A">A</option>
</select>
<button onclick="myFunction()">test</button>

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

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

</body>
</html>

The code above is rendered as follows:

Example 3

The following code shows how to get the label value of the selected option in a drop-down list.


<!DOCTYPE html>
<html>
<body>
<!-- ww  w  . j ava 2 s .co m-->
Select your favorite car:
<br>
<select id="mySelect" size="4">
  <option label="A">A</option>
  <option label="A">S</option>
  <option label="B">B</option>
  <option label="D">D</option>
</select>
<button type="button" onclick="myFunction()">test</button>

<script>
function myFunction() {
    var x = document.getElementById("mySelect").selectedIndex;
    console.log(document.getElementsByTagName("option")[x].label);
}
</script>

</body>
</html>

The code above is rendered as follows: