Practical DOM Patterns
This section shows a few common patterns that put together element selection, content modification, style changes, and event handling.
Show/Hide Elements
Toggling visibility is one of the most common UI interactions:
const toggleButton = document.querySelector("#toggle");
const content = document.querySelector("#content");
toggleButton.addEventListener("click", () => {
content.classList.toggle("hidden");
// Update button text to reflect state
const isHidden = content.classList.contains("hidden");
toggleButton.textContent = isHidden ? "Show" : "Hide";
});
The CSS for the hidden class:
.hidden {
display: none;
}
A variation using inline styles for animation:
toggleButton.addEventListener("click", () => {
if (content.style.display === "none") {
content.style.display = "block";
} else {
content.style.display = "none";
}
});
Live Preview
We can update the content while the user types, so the user sees the result right away:
const input = document.querySelector("#name-input");
const preview = document.querySelector("#greeting");
input.addEventListener("input", () => {
const name = input.value.trim();
if (name) {
preview.textContent = `Hello, ${name}!`;
} else {
preview.textContent = "Enter your name above";
}
});
A more complex example with multiple fields:
const titleInput = document.querySelector("#title");
const bodyInput = document.querySelector("#body");
const previewCard = document.querySelector("#preview-card");
function updatePreview() {
const title = titleInput.value || "Untitled";
const body = bodyInput.value || "No content yet...";
previewCard.querySelector(".card-title").textContent = title;
previewCard.querySelector(".card-body").textContent = body;
}
titleInput.addEventListener("input", updatePreview);
bodyInput.addEventListener("input", updatePreview);
Dynamic List Management
Adding and removing items from a list comes up in almost every app:
const form = document.querySelector("#todo-form");
const input = document.querySelector("#todo-input");
const list = document.querySelector("#todo-list");
form.addEventListener("submit", (event) => {
event.preventDefault();
const text = input.value.trim();
if (!text) return;
// Create new list item
const li = document.createElement("li");
li.className = "todo-item";
const span = document.createElement("span");
span.textContent = text;
const deleteBtn = document.createElement("button");
deleteBtn.textContent = "Delete";
deleteBtn.addEventListener("click", () => {
li.remove();
});
li.append(span, deleteBtn);
list.appendChild(li);
// Clear input for next item
input.value = "";
input.focus();
});