HTML Code

JS Paragraphs

How to Manipulate Paragraphs (<p>) Using JavaScript

JavaScript can dynamically change, create, and style paragraphs (<p>) on a webpage.

Changing Paragraph Text

You can update a paragraph’s text using .innerText or .innerHTML.

Example: Change a Paragraph on Button Click

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>JS Paragraph Example</title>
</head>
<body>

<p id=”myPara”>This is the original paragraph text.</p>
<button onclick=”changeText()”>Change Text</button>

<script>
function changeText() {
document.getElementById(“myPara”).innerText = “Paragraph text has been changed!”;
}
</script>

</body>
</html>

JS Paragraph Example

This is the original paragraph text.

Changing Paragraph Style

You can modify the paragraph’s font, color, or size using .style.

Example: Change Paragraph Color

<p id=”styledPara”>This paragraph will change color.</p>
<button onclick=”changeColor()”>Change Color</button>

<script>
function changeColor() {
document.getElementById(“styledPara”).style.color = “red”;
}
</script>

 

This paragraph will change color.

Creating a New Paragraph Dynamically

You can use document.createElement() to add a new paragraph.

Example: Add a New Paragraph

 

<button onclick=”addParagraph()”>Add Paragraph</button>
<div id=”container”></div>

<script>
function addParagraph() {
let newPara = document.createElement(“p”);
newPara.innerText = “This is a new paragraph!”;
document.getElementById(“container”).appendChild(newPara);
}
</script>

Deleting a Paragraph

Use .remove() to delete an existing paragraph.

Example: Remove a Paragraph

<p id=”removePara”>This paragraph will be removed.</p>
<button onclick=”removeParagraph()”>Remove Paragraph</button>

<script>
function removeParagraph() {
document.getElementById(“removePara”).remove();
}
</script>

This paragraph will be removed.

Changing Multiple Paragraphs at Once

Use document.querySelectorAll() to modify multiple <p> elements.

Example: Change All Paragraphs

<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<button onclick=”changeAll()”>Change All Paragraphs</button>

<script>
function changeAll() {
let paragraphs = document.querySelectorAll(“p”);
paragraphs.forEach(p => p.style.color = “blue”);
}
</script>

Paragraph 1

Paragraph 2

Paragraph 3

Scroll to Top