Categories
JavaScript Answers

How to change label text using JavaScript?

Spread the love

To change the text of a label element using JavaScript, you can select the label element using its ID or other suitable selector, and then modify its textContent or innerText property.

For example we write:

<!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 with JavaScript</title>
</head>
<body>

  <label for="inputField" id="myLabel">Original Label Text</label>
  <br>
  <input type="text" id="inputField">
  <button onclick="changeLabelText()">Change Label Text</button>

  <script>
    function changeLabelText() {
      // Select the label element by ID
      var label = document.getElementById("myLabel");

      // Change the label text
      label.textContent = "New Label Text"; // or label.innerText = "New Label Text";
    }
  </script>

</body>
</html>

In this example, when the button is clicked, the changeLabelText() function is called.

Inside this function, the label element with the ID “myLabel” is selected, and its textContent property is updated to “New Label Text”.

We can also use innerText instead of textContent if you want to change only visible text.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *