JAVASCRIPT
Get, Set, and Remove Element Attributes
Discover how to programmatically manage HTML element attributes using JavaScript, including retrieving values, adding new attributes, and removing existing ones.
const imageElement = document.getElementById('myImage');
// Get an attribute
const currentSrc = imageElement.getAttribute('src');
console.log('Current Image Source:', currentSrc);
// Set or update an attribute
imageElement.setAttribute('alt', 'A dynamically set alternative text');
imageElement.setAttribute('data-id', 'image-123'); // Custom data attribute
// Check if an attribute exists
if (imageElement.hasAttribute('width')) {
console.log('Image has a width attribute.');
}
// Remove an attribute
imageElement.removeAttribute('height'); // Assuming 'height' might exist
// Example HTML setup (not part of snippet, but for context):
// <img id="myImage" src="placeholder.jpg" alt="Original Image" width="100" height="100">
How it works: This snippet illustrates how to interact with HTML element attributes. `getAttribute()` retrieves the value of a specified attribute. `setAttribute()` adds a new attribute or changes the value of an existing one. `hasAttribute()` checks for the presence of an attribute, and `removeAttribute()` removes a specified attribute from an element. These methods provide granular control over an element's properties.