HTML **attributes** are the initial values defined in markup. **Properties** are the live DOM object values that may differ. Use `setAttribute`/`getAttribute` for HTML attributes. For typed properties, use direct access: `el.id`, `el.href`, `el.checked`. **dataset** provides a clean API for `data-*` attributes.
1Understanding Modifying Attributes
HTML attributes are the initial values defined in markup. Properties are the live DOM object values that may differ. Use setAttribute/getAttribute for HTML attributes. For typed properties, use direct access: el.id, el.href, el.checked. dataset provides a clean API for data-* attributes.
getAttribute('class') gets the HTML attribute. el.className gets the property. They can differ — attribute is the initial value, property is the current live value.
const img = document.querySelector('img');
// Attributes
console.log(img.getAttribute('src')); // original src
console.log(img.getAttribute('alt')); // alt text
img.setAttribute('src', '/new-image.jpg');
img.setAttribute('loading', 'lazy');
img.removeAttribute('title');2Practical Example
Here is a real-world application of Modifying Attributes showing how it is used in production JavaScript code.
// dataset for data-* attributes
const btn = document.querySelector('[data-user-id="42"]');
console.log(btn.dataset.userId); // '42' (camelCase!)
btn.dataset.role = 'admin'; // sets data-role
console.log(btn.dataset.role); // 'admin'
delete btn.dataset.role; // removes data-role3Best Practices
Follow these guidelines when working with Modifying Attributes:
1. Use dataset for custom data storage (data-* attributes)
2. Use direct properties (el.href, el.checked) for type-safe access
3. Use removeAttribute to fully remove an attribute
Tip: getAttribute('class') gets the HTML attribute. el.className gets the property. They can differ — attribute is the initial value, property is the current live value.
const img = document.querySelector('img');
// Attributes
console.log(img.getAttribute('src')); // original src
console.log(img.getAttribute('alt')); // alt text
img.setAttribute('src', '/new-image.jpg');
img.setAttribute('loading', 'lazy');
img.removeAttribute('title');