DEV Community

Anthony Bañon Arias
Anthony Bañon Arias

Posted on

✨ Everything You Need to Master the DOM

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");
Enter fullscreen mode Exit fullscreen mode

2. document.getElementsByClassName(className)

Returns a live HTMLCollection of all elements with the specified class.

document.getElementsByClassName("card");
Enter fullscreen mode Exit fullscreen mode

3. document.getElementsByTagName(tagName)

Selects all elements with a given tag name.

document.getElementsByTagName("div");
Enter fullscreen mode Exit fullscreen mode

4. document.querySelector(selector)

Returns the first element that matches a CSS selector.

document.querySelector(".highlight");
document.querySelector("#title");
Enter fullscreen mode Exit fullscreen mode

5. document.querySelectorAll(selector)

Returns all elements that match a CSS selector.

document.querySelectorAll(".item");
Enter fullscreen mode Exit fullscreen mode

📃 Content Manipulation

1. innerHTML

Gets or sets the HTML content inside the element, including nested tags.

element.innerHTML = "<strong>Hello!</strong>";
Enter fullscreen mode Exit fullscreen mode

2. innerText

Gets or sets the visible text, taking CSS visibility and layout into account.

element.innerText = "Visible only text";
Enter fullscreen mode Exit fullscreen mode

3. textContent

Gets or sets all text content, including hidden elements (ignores styling).

element.textContent = "Text without rendering";
Enter fullscreen mode Exit fullscreen mode

4. value

Used for form elements like <input>, <textarea>, and <select> to get or set their value.

inputElement.value = "New value";
Enter fullscreen mode Exit fullscreen mode

📅 Styling Elements

1. Inline Styles

Sets inline CSS directly on the element.

element.style.color = "blue";
element.style.backgroundColor = "#f4f4f4";
Enter fullscreen mode Exit fullscreen mode

2. Computed Styles

Returns the computed style (final styles including those from CSS files).

const styles = getComputedStyle(element);
console.log(styles.margin);
Enter fullscreen mode Exit fullscreen mode

🖌️ 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
Enter fullscreen mode Exit fullscreen mode

🧰 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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

⚖️ 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
Enter fullscreen mode Exit fullscreen mode

🔊 Events and Listeners

Add interactivity by responding to events.

element.addEventListener("click", () => {
    console.log("Element clicked!");
});

element.removeEventListener("click", handlerFunction);
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

🌐 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);
}
Enter fullscreen mode Exit fullscreen mode

🚀 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


Thanks for reading! 🚀 You can follow me on Dev.to or connect on LinkedIn for more posts like this!

Top comments (0)