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 usinginnerText
. - 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.
<!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
Contact Us