Change HTML & CSS with JavaScript


With JavaScript, you can dynamically change HTML content and CSS styles on your webpage — without reloading the page. This is the foundation of creating interactive web applications.



1. Changing HTML Content (Text or Tags)

You can use textContent, innerHTML, or innerText to change an element’s content.


Example:

<h1 id="heading">Welcome!</h1>
<button onclick="changeHeading()">Click Me</button>
<script>
function changeHeading() {
document.getElementById("heading").textContent =
"Hello,
JavaScript!";
}
</script>

Output

The <h1> text changes to: Hello, JavaScript!


2. Change HTML Using innerHTML

document.getElementById("heading").innerHTML ="<span
style='color:red'>Changed!</span>";

Use this when adding HTML tags (not just plain text).



3. Changing CSS Styles with JavaScript

You can directly change CSS styles using .style.property.

Example:

<p id="para">Style me!</p>
<button onclick="styleParagraph()">Style</button>
<script>
function styleParagraph() {
const p = document.getElementById("para");
p.style.color = "blue";
p.style.fontSize = "24px";
p.style.backgroundColor = "#f0f0f0";
}
</script>


4. Add or Remove CSS Classes Dynamically


HTML + CSS:

<style>
.highlight {
color: white;
background-color: green;
padding: 10px;
}
</style>
<p id="text">Toggle my style!</p>
<button onclick="toggleHighlight()">Toggle</button>
<script>
function toggleHighlight() {
document.getElementById("text").classList.toggle("highlight");
}
</script>

classList.toggle() adds the class if it's missing and removes it if it exists.



5. Real-World Use Case: Show/Hide Content

<div id="box" style= "display: none;">Hello, I'm visible now!</div>
<button onclick= "toggleBox()">Show/Hide</button>
<script>
function toggleBox() {
const box = document.getElementById("box");
box.style.display = box.style.display === "none" ? "block" :
"none";
}
</script>