The Label object represents an HTML <label> element.
Property | Description |
---|---|
control | Returns the labeled control |
form | Returns a reference to the form that contains the label |
htmlFor | Sets or gets the for attribute of a label |
The Label object supports the standard properties and events.
We can access a <label> element by using getElementById().
<!DOCTYPE html>
<html>
<body>
<label id="myLabel" for="male">Male</label>
<input type="radio" name="sex" id="male" value="male"><br>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<!-- w w w . j a v a 2 s .c o m-->
<script>
function myFunction() {
var x = document.getElementById("myLabel").htmlFor;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
The code above is rendered as follows:
We can create a <label> element by using the document.createElement() method.
<!DOCTYPE html>
<html>
<body>
<!-- ww w. ja v a 2 s . c o m-->
<form id="myForm" action="url">
<input type="radio" name="sex" id="male" value="male">
</form>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
var x = document.createElement("LABEL");
var t = document.createTextNode("Male");
x.setAttribute("for", "male");
x.appendChild(t);
document.getElementById("myForm").insertBefore(x,document.getElementById("male"));
}
</script>
</body>
</html>
The code above is rendered as follows: