JavaScript DOM Manipulation
The DOM (Document Object Model) is a programming interface that represents a web page as a tree of objects. Every element on the page — headings, paragraphs, buttons, images — is a node in this tree. JavaScript can access, change, add, or remove these nodes, making web pages dynamic and interactive.
Think of the DOM as a live map of the webpage. JavaScript is the GPS that navigates and changes the map.
Understanding the DOM Tree
When a browser loads an HTML page, it converts it into a DOM tree structure:
<!-- HTML -->
<html>
<body>
<h1 id="title">Hello World</h1>
<p class="info">Welcome to JavaScript.</p>
</body>
</html>
// DOM Tree (simplified):
// document
// └── html
// └── body
// ├── h1 (id="title")
// └── p (class="info")Selecting Elements
Before modifying an element, it must be selected (targeted) using JavaScript.
getElementById() — Select by ID
let heading = document.getElementById("title");
console.log(heading); // <h1 id="title">Hello World</h1>getElementsByClassName() — Select by Class Name
let items = document.getElementsByClassName("info");
console.log(items[0]); // First element with class "info"getElementsByTagName() — Select by Tag
let paragraphs = document.getElementsByTagName("p");
console.log(paragraphs.length); // Number of <p> elementsquerySelector() — Select First Matching CSS Selector
let heading = document.querySelector("#title"); // By ID
let info = document.querySelector(".info"); // By class
let button = document.querySelector("button"); // By tag
let special = document.querySelector("ul li.active"); // Complex selectorquerySelectorAll() — Select All Matching Elements
let allItems = document.querySelectorAll("li");
allItems.forEach(item => {
console.log(item.textContent);
});Reading and Changing Content
textContent — Get or Set Plain Text
<p id="msg">Original message</p>
let para = document.getElementById("msg");
// Read
console.log(para.textContent); // Original message
// Change
para.textContent = "Updated message!";innerHTML — Get or Set HTML Content
let box = document.getElementById("box");
// Read (includes HTML tags)
console.log(box.innerHTML);
// Set with HTML tags
box.innerHTML = "<strong>Bold Text</strong>";Note: Only use innerHTML with trusted content. Never insert raw user-provided content directly via innerHTML as it can introduce security risks (XSS).
value — For Form Inputs
<input type="text" id="username" />
let input = document.getElementById("username");
input.value = "Priya"; // Set value
console.log(input.value); // Read valueModifying Attributes
getAttribute() and setAttribute()
<img id="photo" src="default.jpg" alt="Profile Photo" />
let img = document.getElementById("photo");
// Read an attribute
console.log(img.getAttribute("src")); // default.jpg
// Change an attribute
img.setAttribute("src", "profile.jpg");
img.setAttribute("alt", "User Photo");Direct Property Access
let link = document.querySelector("a");
link.href = "https://estudy247.com";
link.target = "_blank";Modifying CSS Styles
inline Style Property
let box = document.querySelector(".box");
box.style.backgroundColor = "lightblue";
box.style.color = "white";
box.style.fontSize = "20px";
box.style.padding = "10px";classList — Add, Remove, Toggle CSS Classes
let btn = document.getElementById("myBtn");
btn.classList.add("active"); // Add class
btn.classList.remove("inactive"); // Remove class
btn.classList.toggle("highlighted"); // Toggle (add if absent, remove if present)
btn.classList.contains("active"); // Returns true/falseCreating and Inserting New Elements
createElement() and appendChild()
// Create a new list item and append it to a list
let newItem = document.createElement("li");
newItem.textContent = "New List Item";
let list = document.getElementById("myList");
list.appendChild(newItem); // Adds at the endinsertBefore() — Insert at Specific Position
let parent = document.getElementById("myList");
let reference = document.getElementById("thirdItem");
let newItem = document.createElement("li");
newItem.textContent = "Inserted Item";
parent.insertBefore(newItem, reference); // Insert before thirdIteminsertAdjacentHTML() — Insert HTML at Specific Position
let container = document.getElementById("container");
container.insertAdjacentHTML("beforeend", "<p>Added at the end!</p>");
container.insertAdjacentHTML("afterbegin", "<p>Added at the start!</p>");Removing Elements
// Remove an element directly
let item = document.getElementById("removeMe");
item.remove();
// Remove a child from its parent
let parent = document.getElementById("myList");
let child = document.getElementById("firstItem");
parent.removeChild(child);Cloning Elements
let original = document.getElementById("card");
let clone = original.cloneNode(true); // true = deep clone (includes children)
document.body.appendChild(clone);Traversing the DOM
DOM nodes are connected to each other. JavaScript provides properties to navigate between related nodes.
let element = document.getElementById("middle");
console.log(element.parentElement); // Parent element
console.log(element.children); // All child elements
console.log(element.firstElementChild); // First child element
console.log(element.lastElementChild); // Last child element
console.log(element.nextElementSibling); // Next sibling element
console.log(element.previousElementSibling); // Previous siblingPractical Example — Dynamic List Builder
<!-- HTML -->
<input type="text" id="itemInput" placeholder="Enter item name" />
<button onclick="addItem()">Add</button>
<ul id="shoppingList"></ul>
<script>
function addItem() {
let input = document.getElementById("itemInput");
let list = document.getElementById("shoppingList");
let text = input.value.trim();
if (text === "") {
alert("Please enter an item name.");
return;
}
let newItem = document.createElement("li");
newItem.textContent = text;
// Click to remove item
newItem.addEventListener("click", function() {
this.remove();
});
list.appendChild(newItem);
input.value = ""; // Clear the input
}
</script>Key Points to Remember
- The DOM represents the webpage as a tree of nodes that JavaScript can manipulate
- Use
querySelector()andquerySelectorAll()for flexible CSS-based element selection - Use
textContentfor plain text;innerHTMLfor HTML content (with caution) - Modify styles directly with
element.style.propertyor useclassListfor classes - Create elements with
createElement()and add them withappendChild() - Remove elements with
element.remove() - Traverse the DOM using
parentElement,children,nextElementSibling, etc.
