How to useinnerText in Javascript

  • Create an HTML label with a unique ID.
  • Add a button with an onclick attribute to trigger the text change.
  • Define a JavaScript function (changeTextWithText) to change the label text using innerText.
  • Within the function, get the label element by its ID.
  • Use the innerText property to set the new plain text content.

Syntax:

label_element.innerText = " new_Text ";

Example: In this example, we are using innerText.

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



How to change the text of a label using JavaScript ?

JavaScript provides two built-in properties that allow us to change the text of any element in an HTML document. In this article, we will explore how to use these properties to 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

  • Using innerHTML
  • Using innerText

Similar Reads

Approach 1: Using innerHTML

Create an HTML label with a unique ID.Add a button with an onclick attribute to trigger the text change.Define a JavaScript function (changeTextWithHTML) to change the label text using innerHTML.Within the function, get the label element by its ID.Use the innerHTML property to set the new text with HTML content....

Approach 2: Using innerText

Create an HTML label with a unique ID.Add a button with an onclick attribute to trigger the text change.Define a JavaScript function (changeTextWithText) to change the label text using innerText.Within the function, get the label element by its ID.Use the innerText property to set the new plain text content....

Contact Us