JS Headings
Changing Heading Text
You can modify the text of a heading using .innerText
or .innerHTML
.
Example: Changing an <h1>
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 Headings Example</title>
</head>
<body>
<h1 id=”main-heading”>Hello, World!</h1>
<button onclick=”changeHeading()”>Change Heading</button>
<script>
function changeHeading() {
document.getElementById(“main-heading”).innerText = “Heading Changed!”;
}
</script>
</body>
</html>
Hello, World!
Changing Heading Color & Style
You can change the style using .style
properties.
Example: Change Heading Color
<h2 id=”myHeading”>This is a heading</h2>
<button onclick=”changeColor()”>Change Color</button>
<script>
function changeColor() {
document.getElementById(“myHeading”).style.color = “red”;
}
</script>
This is a heading
Creating a New Heading with JavaScript
You can create a new heading dynamically using document.createElement()
.
Example: Add a New <h3>
<button onclick=”addHeading()”>Add Heading</button>
<div id=”container”></div>
<script>
function addHeading() {
let newHeading = document.createElement(“h3”);
newHeading.innerText = “New Dynamic Heading”;
document.getElementById(“container”).appendChild(newHeading);
}
</script>
Changing Multiple Headings at Once
Use document.querySelectorAll()
to select multiple headings and modify them.
Example: Change All <h2>
Elements
<h2>Heading 1</h2>
<h2>Heading 2</h2>
<h2>Heading 3</h2>
<button onclick=”changeAllHeadings()”>Change All</button>
<script>
function changeAllHeadings() {
let headings = document.querySelectorAll(“h2”);
headings.forEach(h => h.style.color = “blue”);
}
</script>