How to change label text using JavaScript?

Estimated read time 1 min read

To change the text of a label in JavaScript, you can use the innerHTML property of the label element. Here’s an example:

<label id="label">Original Label Text</label>
<button id="button">Change Label Text</button>

<script>
  let button = document.getElementById("button");
  let label = document.getElementById("label");

  button.addEventListener("click", function() {
    label.innerHTML = "New Label Text";
  });
</script>

In this example, we first select the button and label elements using document.getElementById. Then, we add an event listener to the button that changes the innerHTML of the label when the button is clicked.

You can also use the textContent property to change the text of a label, like this:

label.textContent = "New Label Text";

The textContent property sets the text content of an element, whereas innerHTML sets the HTML content of an element. If you want to set plain text, use textContent, but if you want to set HTML content, use innerHTML.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply