Engineering note · Javascript

Dynamically Update Attribute Values

By Published Updated

Javascript

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.

CODE SAMPLE Code snippet
<!-- 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:

CODE SAMPLE Code snippet
<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>

More engineering notes

Inject a Script into Document Head or Body Tags

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

Apply Styles to Multiple Elements

Apply a style to multiple elements at once by adding a class. Here highlighting selected list items...