DOM Manipulation represents the process of programmatically creating new HTML nodes, altering existing text and markup, modifying CSS presentation classes, and removing obsolete elements from the document tree in real time.
The safe, modern standard for generating elements uses document.createElement():
// Step 1: Create the element
const newCard = document.createElement("div");
// Step 2: Configure classes, attributes, and content
newCard.classList.add("student-card", "active");
newCard.setAttribute("data-id", "104");
newCard.textContent = "Vikram Aditya (Semester 4)";
// Step 3: Append to an existing parent container in the DOM
const container = document.getElementById("student-list");
container.appendChild(newCard); // Appends as last child
classListconst notificationBox = document.querySelector(".toast-notification");
// Add classes
notificationBox.classList.add("visible", "success");
// Remove a class
notificationBox.classList.remove("hidden");
// Toggle class (removes if present, adds if missing - perfect for dark mode!)
notificationBox.classList.toggle("dark-theme");
// Check class existence (returns boolean)
if (notificationBox.classList.contains("success")) {
console.log("Operation was completed successfully!");
}
DocumentFragmentWhen generating hundreds of elements (like search results or blog post feeds), updating the live DOM in a loop triggers severe browser lag. A DocumentFragment optimizes this into a single atomic operation:
const itemsData = ["HTML5", "CSS3", "JavaScript", "React", "Node.js"];
const listContainer = document.getElementById("tech-list");
// Create in-memory fragment
const fragment = document.createDocumentFragment();
itemsData.forEach(tech => {
const li = document.createElement("li");
li.textContent = tech;
li.classList.add("tech-item");
fragment.appendChild(li); // Assembled in memory (ZERO browser reflow!)
});
// Single atomic injection to live DOM:
listContainer.appendChild(fragment);
Exam Question: "How do you remove an element from the DOM in modern JavaScript?"
// Modern Standard (ES6+):
const banner = document.querySelector(".promo-banner");
banner.remove(); // Removes itself directly!
// Legacy DOM Level 2 approach:
// banner.parentNode.removeChild(banner);
How do you respond when a user clicks a button, types on the keyboard, or scrolls? Proceed to: JavaScript Event Handling & Listeners →
Accelerate your JavaScript mastery by studying these tightly connected core tutorials:
Finding elements with querySelector.
Connecting user actions to DOM updates.
Reading input values and showing validation UI.