JavaScript DOM Manipulation Tutorial

📖 10 min read 🏷️ #JavaScript, #DOM, #Beginner, #Interactive
The Document Object Model (DOM) is the bridge between JavaScript and HTML. DOM manipulation lets you dynamically change page content, styles, and structure in response to user actions — the foundation of interactive web pages.
1

What Is the DOM?

The DOM represents your HTML document as a tree of objects. Every HTML element is a node in this tree. JavaScript can access, create, modify, and delete any node. This allows real-time updates without page reloads.

2

Selecting Elements

Use document.getElementById("id") for single elements by ID. document.querySelector(".class") returns the first match. document.querySelectorAll("div") returns all matching elements as a NodeList. Also: getElementsByClassName, getElementsByTagName.

3

Modifying Content

Change text with element.textContent = "new text". Insert HTML with element.innerHTML = "bold". Modify attributes with element.setAttribute("src", "image.jpg"). Change styles with element.style.backgroundColor = "blue".

4

Creating and Removing Elements

Create new elements: document.createElement("div"), then add text, attributes, and styles. Insert with parent.appendChild(child) or parent.insertBefore(new, reference). Remove with element.remove() or parent.removeChild(child).

5

Event Handling

Add interactivity with event listeners: element.addEventListener("click", function). Common events: click, submit, mouseover, mouseout, keydown, input, change. Use event.target to identify which element triggered the event.

6

Practical Examples

Build a to-do list: create, complete, and delete items dynamically. Create an image gallery with lightbox: click thumbnails to show full images. Build a form with live validation: show/hide error messages as users type.

← Back to All Tutorials