Manipulating HTML Elements with JavaScript
#Manipulating HTML Elements with JavaScript
One of the most powerful features of JavaScript is its ability to manipulate HTML elements in real time. From changing text and styles to dynamically adding or removing elements, JavaScript makes web pages interactive and dynamic. In this article, you’ll learn how to select, modify, and create HTML elements using JavaScript.
Manipulating the DOM (Document Object Model) allows you to:
Update content without refreshing the page
Respond to user input
Create interactive interfaces
Validate forms dynamically
Use JavaScript to select elements before modifying them. Common methods include:
// Select by ID
const title = document.getElementById("main-title");
// Select by class
const buttons = document.getElementsByClassName("btn");
// Select by tag
const paragraphs = document.getElementsByTagName("p");
// Select using CSS selectors
const firstBtn = document.querySelector(".btn");
const allBtns = document.querySelectorAll(".btn");
You can change text or HTML inside an element:
document.getElementById("main-title").innerText = "Welcome to JavaScript!";
document.getElementById("content").innerHTML = "<strong>Updated Content</strong>";
Update the appearance of elements:
const box = document.getElementById("box");
box.style.backgroundColor = "lightblue";
box.style.fontSize = "20px";
const newParagraph = document.createElement("p");
newParagraph.innerText = "This is a new paragraph.";
document.body.appendChild(newParagraph);
const oldParagraph = document.getElementById("oldPara");
oldParagraph.remove();
const box = document.getElementById("box");
box.classList.add("highlight");
box.classList.remove("hidden");
box.classList.toggle("active");
const box = document.getElementById("box");
function toggleBox() {
if (box.style.display === "none") {
box.style.display = "block";
} else {
box.style.display = "none";
}
}
<button onclick="toggleBox()">Toggle Box</button>
<div id="box">You can hide or show me.</div>
<h2 id="heading">Original Heading</h2>
<button onclick="changeHeading()">Change Heading</button>
<script>
function changeHeading() {
document.getElementById("heading").innerText = "New Heading!";
}
</script>
Manipulating HTML elements with JavaScript gives you the power to create rich, interactive user experiences. Whether you’re building a simple to-do list or a dynamic web app, understanding how to select and modify DOM elements is key. Practice these techniques, and you’ll quickly level up your front-end development skills!