JAVASCRIPT
Managing Element Attributes (Data attributes, href, src, etc.)
Understand how to dynamically get, set, and remove attributes on DOM elements using getAttribute, setAttribute, and removeAttribute methods.
function manageElementAttributes(elementId, dataAttributeKey, dataAttributeValue) {
const element = document.getElementById(elementId);
if (!element) {
console.error(`Element with ID '${elementId}' not found.`);
return;
}
// Get an attribute
const existingHref = element.getAttribute('href');
console.log(`Existing href: ${existingHref}`);
// Set an attribute (e.g., changing a link's destination or an image's source)
element.setAttribute('href', 'https://new-link.com');
console.log(`New href set to: ${element.getAttribute('href')}`);
// Set a data attribute (useful for custom data associated with elements)
element.setAttribute(`data-${dataAttributeKey}`, dataAttributeValue);
console.log(`Data attribute 'data-${dataAttributeKey}' set to: ${element.dataset[dataAttributeKey]}`);
// Remove an attribute
// element.removeAttribute('title');
// console.log('Title attribute removed.');
}
// Example usage:
// <a id="myLink" href="https://old-link.com" title="Old Title">Click Me</a>
manageElementAttributes('myLink', 'customid', '12345');
How it works: This snippet demonstrates the core functions for interacting with element attributes. It shows how to retrieve an attribute's value using `getAttribute`, set or update an attribute using `setAttribute` (useful for changing sources of images or destinations of links), and access data attributes via the `dataset` property, which is vital for dynamic content and interactive components.