← Back to all snippets
JAVASCRIPT

Update Standard HTML Element Attributes

Learn to modify common HTML attributes like 'src', 'href', or 'id' for existing DOM elements using JavaScript's `setAttribute` method, enabling dynamic content changes.

const myImage = document.getElementById('productImage');
if (myImage && myImage.tagName === 'IMG') {
  myImage.setAttribute('src', 'new-image.jpg');
  myImage.setAttribute('alt', 'New Product Image');
}

const myLink = document.querySelector('.call-to-action');
if (myLink && myLink.tagName === 'A') {
  myLink.setAttribute('href', '/new-destination');
}
How it works: This snippet shows how to change standard HTML attributes like `src` for an image or `href` for a link using `setAttribute()`. It first selects the target element and then updates its specified attributes dynamically, useful for modifying image sources, link destinations, or other element properties.

Need help integrating this into your project?

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

Hire DigitalCodeLabs