JAVASCRIPT
Manage Element Attributes Dynamically
Learn to dynamically set, get, and remove HTML element attributes like `src`, `href`, or custom attributes using JavaScript's attribute methods for interactivity.
const myImage = document.getElementById('productImage');
if (myImage) {
// Set a new attribute or update an existing one
myImage.setAttribute('src', 'new-product-image.jpg');
myImage.setAttribute('alt', 'Updated product photo');
// Get the value of an attribute
const currentSrc = myImage.getAttribute('src');
console.log('Current image source:', currentSrc);
// Check if an attribute exists
if (myImage.hasAttribute('data-id')) {
console.log('Image has data-id attribute.');
}
// Remove an attribute
// myImage.removeAttribute('title');
}
How it works: This code illustrates how to interact with HTML attributes of an element using JavaScript. `setAttribute()` is used to add new attributes or change the value of existing ones. `getAttribute()` retrieves the current value of a specified attribute. `hasAttribute()` checks for the presence of an attribute, and `removeAttribute()` is used to completely remove an attribute from an element. These methods are crucial for dynamically altering element behavior, appearance, and accessibility.