The following code example demonstrates How to Change the Content of a Paragraph Using JavaScript.

In order to change the content of a paragraph dynamically using JavaScript, first we place the paragraph on the document by using the <p> tag. Also, we specify its ID attribute. Further, we place a button on the page that has an onClick event handler. With the help of that event handler, we fetch the paragraph by calling the getElementById() function and passing the Id of the paragraph as its parameter. Then, we take the input from the user by using the prompt() function. After that we set the innerHTML property of the paragraph.

<html>
  <head>
    <title>JavaScript Events</title>
    <script>
      function f1(x)
      {
         str=prompt('Enter some text....');
         var x=document.getElementById('d1');
         x.innerHTML=str;
      }
    </script>
    <style>
       div{
         margin: 100px;
         padding: 50px;
         border: 2px black solid;
         text-align: center;
        }
    </style>
  </head>
  <body>
	<div>
		<button onclick="f1()">Change Content</button>
  		<p id="d1">Original Content of the Paragraph</p>
        </div>
  </body>
</html>

Output

An Example Demonstrating How to Change the Content of a Paragraph Using JavaScript
An Example Demonstrating How to Change the Content of a Paragraph Using JavaScript

When user clicks on the button, a dialog box appears that allow user to enter some text. Once user enters the data and clicks on the OK button, the script changes the content of the paragraph. The following figure demonstrates the output.

Taking Input from the User using the prompt() function
Taking Input from the User using the prompt() function
Changing the Content
Changing the Content

Further Reading

Evolution of JavaScript from ES1 to ES2020

Introduction to HTML DOM Methods in JavaScript

JavaScript Practice Exercise

Understanding Document Object Model (DOM) in JavaScript

What is Asynchronous JavaScript?

Understanding JSON Web Tokens

Arrow Functions in JavaScript

Understanding HTTP Requests and Responses

Princites