| Javascript-DOM-Manipulation | Javascript Form Validation | |
Javascript: Best Practices for DOM Operations |
DOM operations are powerful but can easily become inefficient or messy if not handled carefully. Here are some best practices for DOM manipulation that will keep your code clean, performant, and maintainable:
document.addEventListener("DOMContentLoaded", () => {
// Safe to manipulate DOM here
});
// ❌ Inefficient
document.getElementById("title").textContent = "Hello";
document.getElementById("title").style.color = "blue";
// ✅ Efficient
const title = document.getElementById("title");
title.textContent = "Hello";
title.style.color = "blue";
const firstItem = document.querySelector(".list-item");
const allItems = document.querySelectorAll(".list-item");
const box = document.getElementById("box");
box.classList.add("highlight");
box.classList.remove("hidden");
box.classList.toggle("active");
const list = document.getElementById("myList");
const fragment = document.createDocumentFragment();
for (let i = 1; i <= 5; i++) {
const li = document.createElement("li");
li.textContent = "Item " + i;
fragment.appendChild(li);
}
list.appendChild(fragment); // One reflow instead of five
document.getElementById("myList").addEventListener("click", (e) => {
if (e.target.tagName === "LI") {
console.log("Clicked:", e.target.textContent);
}
});
// Safer element.textContent = "Hello World";
function handleClick() {
console.log("Clicked!");
}
button.addEventListener("click", handleClick);
// Later
button.removeEventListener("click", handleClick);
👉 Following these practices will make your DOM code faster, cleaner, and safer.
Add tasks, mark them complete, and remove them — all while following DOM best practices.
| Javascript-DOM-Manipulation | Javascript Form Validation | |