JAVASCRIPT
Get and Set HTML Element Attributes
Understand how to programmatically read and modify standard HTML attributes like `src`, `href`, or `alt` on any DOM element using JavaScript.
const myImage = document.getElementById('myImage');
const myLink = document.getElementById('myLink');
if (myImage) {
// Get an attribute
const currentSrc = myImage.getAttribute('src');
console.log('Current image src:', currentSrc);
// Set an attribute
myImage.setAttribute('alt', 'A dynamically set alternative text');
myImage.setAttribute('src', 'https://via.placeholder.com/150/FF0000/FFFFFF?text=NewImage');
}
if (myLink) {
// Get the href attribute
const currentHref = myLink.getAttribute('href');
console.log('Current link href:', currentHref);
// Set the href attribute
myLink.setAttribute('href', 'https://www.google.com');
myLink.textContent = 'Go to Google';
}
How it works: This code illustrates how to interact with HTML element attributes. `element.getAttribute('attributeName')` retrieves the value of a specified attribute (e.g., `src`, `alt`, `href`). `element.setAttribute('attributeName', 'newValue')` is used to update or add an attribute with a new value. This is fundamental for dynamically changing image sources, link destinations, or other standard element properties.