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.
HTML
<!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> |
Output:

Example 2: This example changes the text of a label using JavaScript.
html
<!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> |
Output:

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.





Please Login to comment...