How to change the text of a label using JavaScript ?

Given an HTML document and the task is to change the text of a label using JavaScript.

What is a label ?
The <label>tag is used to provide a usability improvement for mouse users i.e, if a user clicks on the text within the <label> element, it toggles the control.

Approach:



  • Create a label element and assign an id to that element.
  • Define a button that is used to call a function. It acts as a switch to change the text in the label element.
  • Define a javaScript function, that will update the label text.
  • Use the innerHTML property to change the text inside the label. The innerHTML property sets or returns the HTML content of an element.

Example 1: This example implements the above approach.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to change the text of
        a label using JavaScript ?
    </title>
</head>
  
<body style="text-align:center;">
      
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
  
    <h4>
        Click on the button to change
        the text of a label
    </h4>
  
    <label id = "GFG">
        Welcome to GeeksforGeeks
    </label>
      
    <br>
      
    <button onclick="myGeeks()">
        Click Here!
    </button>
  
    <script>
        function myGeeks() {
            document.getElementById('GFG').innerHTML
                = 'A computer science portal for geeks';
        }
    </script>
</body>
  
</html>      

chevron_right


Output:

  • Before Click on the Button:
  • After Click on the Button:

Example 2: This example changes the text of a label using JavaScript.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to change the text of
        a label using JavaScript ?
    </title>
</head>
  
<body style="text-align:center;">
      
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
  
    <h4>
        Click on the button to change
        the text of a label
    </h4>
  
    <label id = "GFG">
        Welcome to GeeksforGeeks
    </label>
      
    <br>
      
    <button onclick="myGeeks()">
        Click Here!
    </button>
  
    <script>
        function myGeeks() {
            var x = document.getElementById("GFG");
              
            if (x.innerHTML === "Welcome to GeeksforGeeks") {
                x.innerHTML = "A computer science portal for geeks";
            } else {
                x.innerHTML = "Welcome to GeeksforGeeks";
            }
        }
    </script>
</body>
  
</html>

chevron_right


Output:

  • Before Click on the Button:
  • After Click on the Button:


My Personal Notes arrow_drop_up

Recommended Posts: