JAVASCRIPT
Set and Get HTML Element Attributes
Learn to programmatically set and retrieve custom or standard attributes on any HTML element using JavaScript's `setAttribute()` and `getAttribute()` methods, enhancing dynamic content and interactivity.
// Assume an HTML element like: <img id="myImage" src="old-image.jpg" data-id="123">
const myImage = document.getElementById('myImage');
// Get an attribute's value
const currentSrc = myImage.getAttribute('src');
console.log('Current SRC:', currentSrc); // old-image.jpg
const dataId = myImage.getAttribute('data-id');
console.log('Data ID:', dataId); // 123
// Set or update an attribute's value
myImage.setAttribute('src', 'new-image.png');
myImage.setAttribute('alt', 'A new descriptive alt text');
myImage.setAttribute('data-status', 'loaded');
// Check updated values
console.log('Updated SRC:', myImage.getAttribute('src')); // new-image.png
console.log('Updated Data Status:', myImage.getAttribute('data-status')); // loaded
// Remove an attribute
myImage.removeAttribute('data-id');
console.log('Data ID after removal:', myImage.getAttribute('data-id')); // null
How it works: This snippet demonstrates how to interact with HTML element attributes using `getAttribute()`, `setAttribute()`, and `removeAttribute()`. These methods are crucial for dynamically changing element properties like image sources (`src`), links (`href`), custom data attributes (`data-*`), or any other standard HTML attribute. They provide a robust way to manipulate the HTML structure and behavior of elements based on JavaScript logic.