DOM Manipulation
Changing Content
JavaScript
const heading = document.querySelector("h1"); // textContent — plain text only (safe, no XSS risk) heading.textContent = "New Heading"; heading.textContent // "New Heading" // innerHTML — can include HTML tags (careful with user input!) heading.innerHTML = "<span class='highlight'>New</span> Heading"; // innerText — respects CSS (hidden elements return "") // Use textContent for most cases — it's faster
Changing Attributes
JavaScript
const img = document.querySelector("img"); const link = document.querySelector("a"); // Direct property access (fastest) img.src = "photo.jpg"; img.alt = "Profile photo"; link.href = "https://example.com"; // getAttribute / setAttribute (for custom or non-standard attributes) img.setAttribute("loading", "lazy"); img.getAttribute("src"); // "photo.jpg" img.removeAttribute("loading"); // data- attributes const btn = document.querySelector("[data-id]"); btn.dataset.id // reads data-id btn.dataset.color = "blue"; // sets data-color
classList — CSS Class Management
JavaScript
const el = document.querySelector(".card"); el.classList.add("active"); // add class el.classList.remove("hidden"); // remove class el.classList.toggle("open"); // add if absent, remove if present el.classList.contains("active"); // true/false el.classList.replace("old", "new"); // swap classes el.classList.add("a", "b", "c"); // add multiple
Changing Styles
JavaScript
const box = document.querySelector(".box"); // Inline styles (camelCase for CSS properties) box.style.backgroundColor = "#6c63ff"; box.style.fontSize = "1.5rem"; box.style.display = "none"; // Better: use classList — keeps style logic in CSS box.classList.add("hidden"); // .hidden { display: none } // CSS custom properties via JS document.documentElement.style.setProperty('--primary', '#e74c3c');
Creating & Adding Elements
JavaScript
// Create const card = document.createElement("div"); card.className = "card"; card.innerHTML = `<h3>New Card</h3><p>Content here</p>`; // Append to DOM const container = document.querySelector(".cards-grid"); container.append(card); // add at end container.prepend(card); // add at start // Remove card.remove(); // Replace const old = document.querySelector(".old-card"); old.replaceWith(card);