JAVASCRIPT
Get and Set Standard HTML Element Attributes
Explore how to programmatically retrieve, modify, check existence, and remove standard HTML attributes like 'src', 'href', 'id', or 'class' using JavaScript DOM methods.
const myImage = document.getElementById('myImage');
if (myImage) {
// Get an attribute's value
const currentSrc = myImage.getAttribute('src');
console.log('Current image source:', currentSrc); // e.g., 'old-image.jpg'
// Set a new attribute value
myImage.setAttribute('src', 'new-image.jpg');
myImage.setAttribute('alt', 'A new descriptive alt text for the image');
console.log('Updated image source:', myImage.getAttribute('src'));
// Check if an attribute exists
if (myImage.hasAttribute('title')) {
console.log('Image has a title attribute:', myImage.getAttribute('title'));
} else {
console.log('Image does not have a title attribute.');
myImage.setAttribute('title', 'This is a dynamically added title');
}
// Remove an attribute
myImage.removeAttribute('data-original-src'); // Useful for cleaning up attributes
console.log('Checked if data-original-src exists after removal:', myImage.hasAttribute('data-original-src'));
} else {
console.error('Image element with ID "myImage" not found.');
}
// Example HTML for context:
// <img id="myImage" src="old-image.jpg" alt="An old image" data-original-src="old-image.jpg">
How it works: This snippet illustrates how to interact with standard HTML attributes (like `src`, `alt`, `title`) using `getAttribute()`, `setAttribute()`, `hasAttribute()`, and `removeAttribute()`. These methods provide precise programmatic control over an element's characteristics, enabling dynamic content updates, such as changing an image source, modifying a link's destination, or toggling element visibility via attributes. This is fundamental for building interactive and data-driven web applications.