Open In App

How to change the text of a label using JavaScript ?

To change the text of a label, JavaScript allows us to use two inbuilt properties to change the text of any element in the HTML document. In this article, we are going to see how we can change the text of a label using JavaScript.

Below are the approaches used to change the text of a label using JavaScript:



Table of Content

Approach 1: Using innerHTML

Syntax:

label_element.innerHTML = "new_Text";

Example: In this example, we are using innerHTML.






<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,
                 initial-scale=1.0">
    <title>Change Label Text - innerHTML</title>
</head>
 
<body>
    <!-- HTML label with an ID -->
    <label id="labelWithHTML">Initial Text</label>
 
    <!-- Button to trigger text change -->
    <button onclick="changeTextWithHTML()">
        Change Text</button>
 
    <script>
        // Function to change label text with HTML content
        function changeTextWithHTML() {
            let labelElement = document
                .getElementById("labelWithHTML");
            labelElement.innerHTML =
                "<em>New Text</em> using <strong>innerHTML</strong>";
        }
    </script>
</body>
 
</html>

Output:

Approach 2: Using innerText

Syntax:

label_element.innerText = " new_Text ";

Example: In this example, we are using innerText.




<!DOCTYPE html>
<html lang="en">
 
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width,
                 initial-scale=1.0">
  <title>Change Label Text - innerText</title>
</head>
 
<body>
  <!-- HTML label with an ID -->
  <label id="labelWithText">Initial Text</label>
 
  <!-- Button to trigger text change -->
  <button onclick="changeTextWithText()">Change Text</button>
 
  <script>
    // Function to change label text with plain text content
    function changeTextWithText() {
      let labelElement = document.getElementById("labelWithText");
      labelElement.innerText =
"New Text using innerText";
    }
  </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.


Article Tags :