Episode 35 of 46

Changing HTML Tag Attributes

Learn how to get, set, and remove HTML attributes with JavaScript.

JavaScript lets you read, change, and remove HTML attributes like src, href, class, id, and custom data attributes.

Getting Attributes

let link = document.querySelector("a");
let img = document.querySelector("img");

link.getAttribute("href");     // "https://example.com"
img.getAttribute("src");       // "photo.jpg"
img.getAttribute("alt");       // "A photo"

Setting Attributes

// Change an existing attribute
link.setAttribute("href", "https://google.com");
img.setAttribute("src", "new-photo.jpg");

// Add a new attribute
link.setAttribute("target", "_blank");

// Direct property access (common attributes)
img.src = "another-photo.jpg";
link.href = "https://example.com";
link.id = "main-link";

Removing Attributes

link.removeAttribute("target");
img.removeAttribute("alt");

Class Manipulation

let box = document.querySelector(".box");

// classList methods (recommended)
box.classList.add("active");
box.classList.remove("hidden");
box.classList.toggle("highlight");     // Add if missing, remove if present
box.classList.contains("active");      // true or false
box.classList.replace("old", "new");

Data Attributes

// HTML: <div data-user-id="42" data-role="admin">

let el = document.querySelector("[data-user-id]");

// Access via dataset property
console.log(el.dataset.userId);   // "42" (camelCase!)
console.log(el.dataset.role);     // "admin"

// Set data attribute
el.dataset.status = "active";
// Adds: data-status="active"