Javascript Reference - HTML DOM Label htmlFor Property








The for attribute from label element specifies which form element a label is bound to.

The htmlFor property sets or gets the for attribute of a label.

Browser Support

htmlFor Yes Yes Yes Yes Yes

Syntax

Return the htmlFor property.

var v = labelObject.htmlFor

Set the htmlFor property.

labelObject.htmlFor=id




Property Values

Value Description
id The id of the element the label is bound to

Return Value

A String type value representing the id of the element the label is bound to.

Example

The following code shows how to Change the value of the value attribute of a label.


<!DOCTYPE html>
<html>
<body>
<form>
  <label id="myLabel" for="male">Male</label>
  <input type="radio" name="sex" id="male" value="male"><br>
</form><!-- w ww. j a v a2s.  c  om-->
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
    document.getElementById("myLabel").htmlFor = "newValue";
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to get the value of the for attribute of a label.


<!DOCTYPE html>
<html>
<body>
<!-- w w  w .j a va  2 s. c om-->
<form>
  <label id="myLabel" for="male">Male</label>
  <input type="radio" name="sex" id="male" value="male"><br>
</form>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {
    var x = document.getElementById("myLabel").htmlFor;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The code above is rendered as follows: