Javascript Reference - HTML DOM Label Object








The Label object represents an HTML <label> element.

Label Object Properties

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

Standard Properties and Events

The Label object supports the standard properties and events.

Example

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:





Example 2

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: