JavaScript Code


How to change text of paragraph using JavaScript?


Tutorials using JS

Change text of Paragraph using JavaScript

In this tutorial, you shall learn how to given a paragraph element, change the text content of the paragraph element using JavaScript.

Solution

To set or change the text of a paragraph element using JavaScript, we can use Element.innerText property. Get the paragraph element and set its innerText property with the required text.

paragraphElement.innerText = 'hello world';

Program

When user clicks on the button, we get the paragraph with the id message, and set its text using innerText property.

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<button id="myBtn">Click me</button>
<p id="message">This is a paragraph.</p>

<script>
document.getElementById("myBtn").addEventListener("click", function() {
  const myPara = document.getElementById("message");
  //set the text in paragraph element
  myPara.innerText = "This is a coded message.";
});
</script>

</body>
</html>


Copyright @2022