← Back to all snippets
JAVASCRIPT

Modifying HTML Element Attributes

Dynamically change common HTML attributes like `src`, `href`, or `disabled` on elements using JavaScript's `setAttribute` and `removeAttribute` methods for interactive UIs.

const myImage = document.getElementById('myImage');
const myLink = document.getElementById('myLink');
const myButton = document.getElementById('myButton');

// Set a new image source
myImage.setAttribute('src', 'new-image.jpg');
myImage.setAttribute('alt', 'A new descriptive alt text');

// Update link destination
myLink.setAttribute('href', 'https://new-destination.com');

// Disable a button
myButton.setAttribute('disabled', 'true');

// Remove an attribute (e.g., make button re-enabled)
myButton.removeAttribute('disabled');
How it works: This snippet demonstrates how to manipulate various attributes of HTML elements. It uses `setAttribute()` to add or change an attribute's value, for example, updating an image's source or a link's URL. It also shows `removeAttribute()` to completely remove an attribute, such as disabling and re-enabling a button.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs