DOM Manipulation in JavaScript (Complete Guide with Examples for Beginners)”
DOM Manipulation in JavaScript
with Examples
Complete guide — selecting elements, getElementById, querySelector, innerHTML vs textContent, attributes, styling, creating & removing elements, event listeners, building dynamic UI, and best practices.
What is DOM Manipulation? — Why Every Web Developer Must Master It
DOM Manipulation is the act of using JavaScript to read, change, add, or remove elements on a webpage — without reloading the page. It is the core skill of front-end web development. Every interactive feature you see on a website — a button that shows a dropdown, a form that validates input, a live search that filters results, a modal that pops up — all of it is DOM manipulation.
Without DOM manipulation, websites would be completely static — like documents you can read but never interact with. With it, you can make any webpage respond to user actions in real time, update content dynamically, and create application-like experiences entirely in the browser.
This guide covers every aspect of DOM manipulation from A to Z — all the methods, all the techniques, real code examples you can run today, and the best practices that professional front-end developers follow in 2026.
Selecting Elements — getElementById, querySelector & More
Before you can manipulate anything, you must select the element you want to work with. JavaScript provides multiple selection methods — each suited for different situations. getElementById is the fastest for single elements with a unique id. querySelector is the most flexible, accepting any CSS selector. querySelectorAll returns all matching elements.
// getElementById — by unique id (returns single element) const header = document.getElementById("header"); const btn = document.getElementById("submit-btn"); // querySelector — first match for any CSS selector const byClass = document.querySelector(".highlight"); // class const byId = document.querySelector("#main"); // id const byTag = document.querySelector("h1"); // tag const nested = document.querySelector(".card .title"); // CSS nesting const attr = document.querySelector('[data-id="5"]');// attribute // querySelectorAll — ALL matches (returns NodeList) const allBtns = document.querySelectorAll("button"); const allCards = document.querySelectorAll(".card"); console.log("Total buttons: " + allBtns.length); // Loop through all selected elements allCards.forEach((card, i) => { console.log(`Card ${i+1}: ${card.className}`); });
innerHTML vs textContent — Reading and Changing Page Content
Once you have selected an element, the two most important properties for reading and setting its content are innerHTML and textContent. They look similar but behave very differently — choosing the wrong one can cause security vulnerabilities or unexpected results.
<!-- Assume this HTML on the page: --> <div id="box"><strong>Hello</strong> World</div> const box = document.getElementById("box"); // textContent — reads/sets PLAIN TEXT only (no HTML parsing) console.log(box.textContent); // "Hello World" — strips all HTML tags box.textContent = "<strong>New Content</strong>"; // Shows literally: <strong>New Content</strong> — tags not parsed! // innerHTML — reads/sets content WITH HTML tags interpreted console.log(box.innerHTML); // "<strong>Hello</strong> World" box.innerHTML = "<strong>Bold</strong> and <em>Italic</em>"; // Shows: Bold and Italic — HTML is rendered! // innerText — like textContent but respects CSS visibility console.log(box.innerText); // visible text only // Practical examples const score = document.getElementById("score"); score.textContent = 42; // safe for user data — prevents XSS const card = document.getElementById("card"); card.innerHTML = ` <h3>Sara Khan</h3> <p>JavaScript Developer</p> <button>View Profile</button> `; // build HTML structure dynamically ✅
innerHTML with user-provided data (like form input). It can execute malicious HTML/JS injected by attackers — this is called XSS (Cross-Site Scripting). Always use textContent for displaying user input.Changing Attributes & Styling with JavaScript
DOM manipulation lets you change any HTML attribute (src, href, alt, data-*, disabled, checked) and apply CSS styles directly through JavaScript. The cleanest approach for styling is to add or remove CSS classes rather than setting inline styles directly — this keeps your styling in CSS files where it belongs.
// Changing HTML attributes const link = document.querySelector("a"); link.setAttribute("href", "https://javascript.info"); link.setAttribute("target", "_blank"); console.log(link.getAttribute("href")); // "https://javascript.info" link.removeAttribute("target"); // remove the attribute // Image src change const img = document.querySelector("img"); img.src = "profile.jpg"; img.alt = "User Profile Photo"; // Input handling const input = document.querySelector("input"); input.disabled = true; // disable the input input.value = "Prefilled text"; // Inline styles — direct CSS property changes const box = document.getElementById("box"); box.style.backgroundColor = "#1e1b4b"; box.style.color = "#a5b4fc"; box.style.padding = "20px"; box.style.borderRadius = "12px"; box.style.display = "none"; // hide element box.style.display = "block"; // show element // classList — best practice for toggling styles box.classList.add("active"); // add class box.classList.remove("hidden"); // remove class box.classList.toggle("dark-mode"); // add if missing, remove if present console.log(box.classList.contains("active")); // true console.log([...box.classList]); // see all classes
Creating & Removing Elements — Building the DOM Dynamically
JavaScript can create brand new HTML elements and add them to the page at any time. This is how dynamic lists, cards, notifications, comments, and search results are built on modern websites. You can also remove elements permanently from the DOM.
// Create a new element const newCard = document.createElement("div"); newCard.className = "card"; newCard.innerHTML = ` <h3>New Post Title</h3> <p>This card was created by JavaScript!</p> <button class="delete-btn">Delete ❌</button> `; // Add element to the DOM document.getElementById("container").appendChild(newCard); // end document.body.prepend(newCard); // beginning // insertAdjacentHTML — precise placement const parent = document.getElementById("list"); parent.insertAdjacentHTML("beforeend", "<li>New Item</li>"); // Clone an existing element const template = document.querySelector(".card-template"); const clone = template.cloneNode(true); // true = deep clone clone.querySelector("h3").textContent = "Cloned Card"; parent.appendChild(clone); // Remove elements const toDelete = document.querySelector(".remove-this"); if (toDelete) { toDelete.remove(); // modern way — removes from DOM } // Remove all children from a container const container = document.getElementById("results"); container.innerHTML = ""; // fastest way to clear all children
Adding Event Listeners & Building Dynamic UI
Event listeners are what make DOM manipulation truly interactive. They tell JavaScript to watch for a specific user action (click, keypress, scroll, mouse movement) and run a function when it happens. Combined with DOM manipulation, event listeners let you build fully dynamic, app-like user interfaces.
// Basic event listener const btn = document.getElementById("action-btn"); btn.addEventListener("click", function() { console.log("Button clicked! π"); }); // Multiple events on same element const input = document.querySelector("input"); input.addEventListener("focus", () => input.style.borderColor = "blue"); input.addEventListener("blur", () => input.style.borderColor = "gray"); input.addEventListener("input", () => console.log(input.value)); // Dynamic UI — Complete Tab System const tabs = document.querySelectorAll(".tab"); const panels = document.querySelectorAll(".panel"); tabs.forEach((tab, i) => { tab.addEventListener("click", () => { // Remove active from all tabs and panels tabs.forEach(t => t.classList.remove("active")); panels.forEach(p => p.classList.remove("active")); // Add active only to clicked tab and its panel tab.classList.add("active"); panels[i].classList.add("active"); }); }); // Event delegation — one listener for many elements document.getElementById("list").addEventListener("click", (e) => { if (e.target.tagName === "LI") { e.target.classList.toggle("done"); console.log("Toggled: " + e.target.textContent); } });
DOM Manipulation Best Practices — Write Professional Code
✅ Cache DOM selections — store selected elements in const, don't query the DOM repeatedly
✅ Use classList over inline styles — add/remove CSS classes keeps styling in CSS files
✅ Use textContent for user data — never innerHTML with user input (prevents XSS attacks)
✅ Use event delegation — one listener on a parent handles all children efficiently
✅ Batch DOM changes — make multiple changes before updating the DOM to minimize repaints
✅ Use DocumentFragment — build multiple elements off-screen and insert once
✅ Clean up event listeners — remove listeners when elements are removed to prevent memory leaks
✅ Complete Summary — DOM Manipulation in JavaScript
π Content: textContent (safe, plain text) vs innerHTML (renders HTML tags)
π§ Attributes: setAttribute · getAttribute · removeAttribute — change any HTML attribute
π¨ Styling: classList.add/remove/toggle — preferred · style.property for one-off changes
➕ Create: createElement → set content → appendChild/prepend — build new elements
π️ Remove: element.remove() or container.innerHTML = "" to clear all children
π±️ Events: addEventListener — respond to click, input, scroll, keypress, and more
⭐ Best Practice: Cache queries · use classList · textContent for user data · event delegation
DOM manipulation is the most practical JavaScript skill for beginners to master. The best way to learn it is to build projects — a to-do app, a quiz app, a color picker, a dynamic form. Each project will force you to use getElementById, querySelector, textContent, classList, addEventListener, and createElement. After building 3–4 small projects with DOM manipulation, these methods become completely natural. Start coding real projects today!
π» for more posts
- π history of JavaScript
- π variables in JavaScript
- π data types in JavaScript
- π Functions in JavaScript
- π Conditional statements in JavaScript
- π objects in JavaScript
- π loops in JavaScript
- π operators in JavaScript
- π What is DOM in JavaScript
- π JavaScript scope and hoisting
Comments
Post a Comment