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.
htmlFor |
Yes | Yes | Yes | Yes | Yes |
Return the htmlFor property.
var v = labelObject.htmlFor
Set the htmlFor property.
labelObject.htmlFor=id
Value | Description |
---|---|
id | The id of the element the label is bound to |
A String type value representing the id of the element the label is bound to.
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:
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: