Dynamically Update Attribute Values


To change the attributes of multiple elements based on user input or other dynamic conditions. Use setAttribute to update attributes for multiple elements.

Let say you want to show image by selecting from dropdown.

<!-- Dropdown -->
<select id="imageSelector">
     <option value="image1.jpg" data-alt="Image 1 Description">Image 1</option>
     <option value="image2.jpg" data-alt="Image 2 Description">Image 2</option>
     <option value="image3.jpg" data-alt="Image 3 Description">Image 3</option>
</select>

<!-- Show image here -->
<div id="gallery">
   <img id="mainImage" src="default.jpg" alt="Default Image">
</div>

Javascript:

<script>
    document.getElementById('imageSelector').addEventListener('change', function() {

        // get selected item's url and alt 
        const selectedOption = this.options[this.selectedIndex];
        const imageUrl = selectedOption.value;
        const imageAlt = selectedOption.getAttribute('data-alt');

        const mainImage = document.getElementById('mainImage');
        mainImage.setAttribute('src', imageUrl); // set url of image
        mainImage.setAttribute('alt', imageAlt); // set alt attribute of image
    });
</script>

You Might Also Like

Efficiently Append Multiple Elements

Appending multiple elements to the DOM can be inefficient if done individually. Use a document frag...

Inject a Script into Document Head or Body Tags

You can inject js script into the document head dynamically like this : ``` const basicScript = do...