Attributes
Read, set, and remove HTML attributes — work with src, href, data attributes, and any custom attributes on DOM elements.
Attributes
HTML attributes like src, href, data-*, and disabled can all be read and modified through JavaScript. The DOM provides methods to get, set, check, and remove any attribute.
Getting Attributes
var link = document.querySelector('a');
console.log(link.getAttribute('href')); // "https://example.com"
console.log(link.getAttribute('target')); // "_blank" or null
var img = document.querySelector('img');
console.log(img.getAttribute('src')); // "photo.jpg"
console.log(img.getAttribute('alt')); // "A photo"
Setting Attributes
link.setAttribute('href', 'https://newsite.com');
link.setAttribute('target', '_blank');
img.setAttribute('src', 'new-photo.jpg');
img.setAttribute('alt', 'Updated photo');
Checking and Removing
console.log(link.hasAttribute('target')); // true or false
link.removeAttribute('target'); // Removes the attribute entirely
Data Attributes
<div id="ninja" data-name="Ryu" data-rank="5" data-special-move="Hadouken"></div>
var ninja = document.getElementById('ninja');
// Using getAttribute
console.log(ninja.getAttribute('data-name')); // "Ryu"
// Using the dataset property (easier!)
console.log(ninja.dataset.name); // "Ryu"
console.log(ninja.dataset.rank); // "5"
console.log(ninja.dataset.specialMove); // "Hadouken" (camelCase!)
// Setting data attributes
ninja.dataset.level = '10'; // Adds data-level="10"
The dataset property provides a cleaner API for data attributes. Hyphenated names become camelCase: data-special-move becomes dataset.specialMove.
Common Attribute Methods
| Method | Purpose |
|---|---|
getAttribute(name) | Read an attribute value |
setAttribute(name, value) | Set or update an attribute |
hasAttribute(name) | Check if attribute exists |
removeAttribute(name) | Remove an attribute |
element.dataset | Access all data-* attributes as an object |
Key Takeaways
getAttributeandsetAttributework with any attribute — standard or custom- The
datasetproperty provides easy access todata-*attributes - Data attribute names are converted to camelCase in
dataset - Use
hasAttributeto check existence;removeAttributeto delete