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
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.
Further Reading
Evolution of JavaScript from ES1 to ES2020
Introduction to HTML DOM Methods in JavaScript
Understanding Document Object Model (DOM) in JavaScript
What is Asynchronous JavaScript?
Understanding HTTP Requests and Responses
- AI
- Android
- Angular
- ASP.NET
- Augmented Reality
- AWS
- Bioinformatics
- Biometrics
- Blockchain
- Bootstrap
- C
- C#
- C++
- Cloud Computing
- Competitions
- Courses
- CSS
- Cyber Security
- Data Science
- Data Structures and Algorithms
- Data Visualization
- Datafication
- Deep Learning
- DevOps
- Digital Forensic
- Digital Trust
- Digital Twins
- Django
- Docker
- Dot Net Framework
- Drones
- Elasticsearch
- ES6
- Extended Reality
- Flutter and Dart
- Full Stack Development
- Git
- Go
- HTML
- Image Processing
- IoT
- IT
- Java
- JavaScript
- Kotlin
- Latex
- Machine Learning
- MEAN Stack
- MERN Stack
- Microservices
- MongoDB
- NodeJS
- PHP
- Power Bi
- Projects
- Python
- Quantum Computing
- React
- Robotics
- Rust
- Scratch 3.0
- Shell Script
- Smart City
- Software
- Solidity
- SQL
- SQLite
- Tecgnology
- Tkinter
- TypeScript
- VB.NET
- Virtual Reality
- Web Designing
- WebAssembly
- XML