Setting Element Attributes
You'll learn how to read, modify, and remove attributes on DOM elements using JavaScript's built-in methods and properties.
The Core Idea
Once you've created an element with createElement(), it exists in memory but has no attributes yet—no id, no class, no src for images. Setting attributes is like filling out a form for that element, giving it the properties it needs to function and look right when added to the page.
JavaScript gives you four main ways to work with attributes:
setAttribute()
Use setAttribute(name, value) to add or update any attribute:
const img = document.createElement('img');
img.setAttribute('src', 'photo.jpg');
img.setAttribute('alt', 'A beautiful sunset');
getAttribute()
Retrieve an attribute's value as a string:
const source = img.getAttribute('src'); // "photo.jpg"
removeAttribute()
Delete an attribute entirely:
img.removeAttribute('alt');
Direct Property Assignment
For common attributes, you can skip the methods and assign directly:
img.src = 'photo.jpg';
img.alt = 'A beautiful sunset';
img.id = 'hero-image';
This approach is cleaner and often preferred for standard HTML attributes. However, setAttribute() is necessary for data attributes (data-*) or custom attributes.
Think of it this way: Direct property assignment is like using familiar nickname shortcuts with close friends, while setAttribute() is the formal full-name approach that works universally.
When to Use Each
- Use direct properties for standard attributes (easier to read and write)
- Use setAttribute/getAttribute for data attributes, custom attributes, or when working with attribute names dynamically
- Use removeAttribute when you need to completely remove an attribute, not just set it to an empty string
Key Takeaway: Manipulate element attributes using setAttribute(), getAttribute(), removeAttribute(), or direct property assignment—choose based on readability and the attribute type you're working with.