JAVASCRIPT

Update Multiple Element Attributes

Learn to dynamically modify various HTML attributes (like 'src', 'href', or custom data attributes) on an existing element using JavaScript's setAttribute method.

document.addEventListener('DOMContentLoaded', () => {
  const myImage = document.getElementById('myImage');
  const myLink = document.getElementById('myLink');
  const myButton = document.getElementById('updateAttributesButton');

  if (myImage && myLink && myButton) {
    myButton.addEventListener('click', () => {
      // Update image source and alt attributes
      myImage.setAttribute('src', 'https://via.placeholder.com/150/FF0000/FFFFFF?text=NewImage');
      myImage.setAttribute('alt', 'A dynamically updated placeholder image');
      myImage.setAttribute('data-timestamp', Date.now()); // Example of updating a data attribute

      // Update link href and target attributes
      myLink.setAttribute('href', 'https://www.google.com');
      myLink.setAttribute('target', '_blank');
      myLink.textContent = 'Go to Google';

      console.log('Attributes updated!');
    });
  }
});

/* Example HTML for context:
<img id="myImage" src="https://via.placeholder.com/150" alt="Placeholder Image">
<a id="myLink" href="#">My Link</a>
<button id="updateAttributesButton">Update Attributes</button>
*/
How it works: This snippet illustrates how to change multiple attributes of existing HTML elements dynamically using `element.setAttribute()`. When the 'Update Attributes' button is clicked, it modifies the `src`, `alt`, and a custom `data-timestamp` attribute of an image, and the `href` and `target` attributes of a link. This is extremely useful for scenarios where you need to change an image dynamically, update navigation links, or manage state through data attributes without recreating the entire element.

Need help integrating this into your project?

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

Hire DigitalCodeLabs