A Complete Guide to Using the DOM
📚 Introduction
When you first step into web development, one of the most empowering things you can learn is how to interact with the DOM (Document Object Model) using JavaScript. The DOM is essentially the interface between your HTML and your JavaScript code. Being able to select, modify, style, and dynamically manipulate DOM elements is at the heart of making websites interactive and responsive.
In this article, we will explore a comprehensive set of methods to manipulate the DOM. We'll cover everything from selectors, content manipulation, CSS styling, class controls, node traversal, event handling, and creating elements dynamically. Whether you're a beginner or brushing up your skills, this guide will be your go-to reference.
🔍 DOM Selectors
1. document.getElementById(id)
Selects a single element by its ID.
document.getElementById("myTitle");
2. document.getElementsByClassName(className)
Returns a live HTMLCollection of all elements with the specified class.
document.getElementsByClassName("card");
3. document.getElementsByTagName(tagName)
Selects all elements with a given tag name.
document.getElementsByTagName("div");
4. document.querySelector(selector)
Returns the first element that matches a CSS selector.
document.querySelector(".highlight");
document.querySelector("#title");
5. document.querySelectorAll(selector)
Returns all elements that match a CSS selector.
document.querySelectorAll(".item");
📃 Content Manipulation
1. innerHTML
Gets or sets the HTML content inside the element, including nested tags.
element.innerHTML = "<strong>Hello!</strong>";
2. innerText
Gets or sets the visible text, taking CSS visibility and layout into account.
element.innerText = "Visible only text";
3. textContent
Gets or sets all text content, including hidden elements (ignores styling).
element.textContent = "Text without rendering";
4. value
Used for form elements like <input>
, <textarea>
, and <select>
to get or set their value.
inputElement.value = "New value";
📅 Styling Elements
1. Inline Styles
Sets inline CSS directly on the element.
element.style.color = "blue";
element.style.backgroundColor = "#f4f4f4";
2. Computed Styles
Returns the computed style (final styles including those from CSS files).
const styles = getComputedStyle(element);
console.log(styles.margin);
🖌️ Classes: Add, Remove, Toggle
Use the classList
property to manage element classes efficiently.
element.classList.add("active"); // Adds a class
element.classList.remove("hidden"); // Removes a class
element.classList.toggle("dark-mode"); // Toggles a class on/off
element.classList.contains("visible"); // Checks if class exists
🧰 Node Traversal and DOM Relationships
1. Accessing Parent and Child Elements
-
parentNode
: Returns the parent node of the element. -
children
: Returns a live HTMLCollection of the child elements. -
firstElementChild
: Returns the first child that is an element. -
lastElementChild
: Returns the last child that is an element.
const parent = element.parentNode;
const kids = element.children;
const firstChild = element.firstElementChild;
const lastChild = element.lastElementChild;
2. Accessing Sibling Elements
-
previousElementSibling
: Gets the previous sibling that is an element. -
nextElementSibling
: Gets the next sibling that is an element.
const prev = element.previousElementSibling;
const next = element.nextElementSibling;
3. Creating and Inserting Elements
You can dynamically create elements and insert them into the DOM.
const newDiv = document.createElement("div");
newDiv.textContent = "I am new!";
document.body.appendChild(newDiv);
4. Insertion Methods
-
appendChild()
: Adds a node to the end. -
prepend()
: Adds a node to the beginning. -
insertBefore()
: Inserts before a reference node. -
replaceChild()
: Replaces a child node. -
removeChild()
: Removes a child node.
parent.appendChild(child);
parent.prepend(child);
parent.insertBefore(newNode, referenceNode);
parent.replaceChild(newNode, oldNode);
parent.removeChild(child);
⚖️ Attribute Management
Use these methods to manipulate element attributes.
element.setAttribute("src", "image.jpg"); // Sets an attribute
element.getAttribute("href"); // Gets an attribute value
element.removeAttribute("disabled"); // Removes an attribute
element.hasAttribute("checked"); // Checks if attribute exists
🔊 Events and Listeners
Add interactivity by responding to events.
element.addEventListener("click", () => {
console.log("Element clicked!");
});
element.removeEventListener("click", handlerFunction);
Common Events
-
click
: when an element is clicked -
submit
: when a form is submitted -
change
: when an input value changes -
mouseover
: when hovering over an element -
keydown
: when a key is pressed
You can also attach events inline (not recommended for maintainability):
<button onclick="alert('clicked')">Click me</button>
🌐 Dynamic Element Creation Example
function addUser(name, dni) {
const userList = document.getElementById("userList");
const p = document.createElement("p");
p.innerHTML = `<strong>Name:</strong> ${name} | <strong>DNI:</strong> ${dni}`;
userList.appendChild(p);
}
🚀 Conclusion
Manipulating the DOM is the cornerstone of building interactive web applications. Mastering selectors, content updates, dynamic element creation, and event handling will make you a more confident and capable frontend developer. These tools give you full control over how your site behaves and responds to user actions.
Always remember: the DOM is your canvas, and JavaScript is your brush.
📓 References
- Mozilla Developer Network (MDN). (n.d.). Document Object Model (DOM). Retrieved from: https://developer.mozilla.org/en-US/docs/Web/JavaScript
- Mozilla Developer Network (MDN). (n.d.). Working with the DOM. Retrieved from: https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model
Thanks for reading! 🚀 You can follow me on Dev.to or connect on LinkedIn for more posts like this!
Top comments (0)