Quiz Entry - updated: 2026.06.20
How do you read and modify HTML attributes with JavaScript?
Read attributes with getAttribute("name") and change them with setAttribute("name", "value") (or use the matching DOM property directly).
const link = document.querySelector("a");
// Read attribute
const href = link.getAttribute("href");
const target = link.getAttribute("target");
// Set attribute
link.setAttribute("href", "https://example.com");
link.setAttribute("target", "_blank");
Common attributes:
href,src,alt,title,class,iddata-*custom attributesdisabled,checked,selected(boolean)
Alternative: Direct property access:
// Same as setAttribute
link.href = "https://example.com";
// Same as getAttribute
console.log(link.href);
Note: Some attributes differ from properties (e.g., class attribute vs className property).