JAVASCRIPT

Update Multiple Element Attributes and Content Dynamically

Discover how to efficiently update various attributes like `src`, `alt`, and `title`, along with content for a DOM element using JavaScript.

// HTML Structure
/*
<figure>
  <img id="dynamicImage" src="https://via.placeholder.com/150/FF5733/FFFFFF?text=Initial+Image" alt="Initial Placeholder Image">
  <figcaption id="imageCaption">A simple placeholder image.</figcaption>
</figure>
<button id="updateImageBtn">Update Image</button>
*/

const dynamicImage = document.getElementById('dynamicImage');
const imageCaption = document.getElementById('imageCaption');
const updateImageBtn = document.getElementById('updateImageBtn');

let imageCounter = 1;

if (dynamicImage && imageCaption && updateImageBtn) {
  updateImageBtn.addEventListener('click', () => {
    imageCounter++;
    const newSrc = `https://via.placeholder.com/200/33FF57/000000?text=Updated+Image+${imageCounter}`;
    const newAlt = `Dynamically updated image number ${imageCounter}`;
    const newTitle = `Image ${imageCounter} loaded`;
    const newCaptionText = `This is image number ${imageCounter} from the dynamic update.`;

    // Update attributes
    dynamicImage.setAttribute('src', newSrc);
    dynamicImage.setAttribute('alt', newAlt);
    dynamicImage.setAttribute('title', newTitle); // Custom attribute or standard

    // Update content of a sibling element
    imageCaption.textContent = newCaptionText;

    // Example of removing an attribute
    if (imageCounter % 2 === 0) {
        dynamicImage.removeAttribute('data-custom-attribute');
    } else {
        dynamicImage.setAttribute('data-custom-attribute', 'info-added');
    }

    console.log('Image and caption updated.');
  });
}
How it works: This snippet demonstrates how to programmatically update multiple attributes and the textual content of related DOM elements. It uses `element.setAttribute()` to modify standard attributes like `src`, `alt`, and `title`, and `element.textContent` to change the visible text within another element. It also includes an example of `removeAttribute()`. This is fundamental for building interactive interfaces where elements need to visually or functionally change based on user actions or data updates.

Need help integrating this into your project?

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

Hire DigitalCodeLabs