Javascript
To change the attributes of multiple elements based on user input or other dynamic conditions. Use to update attributes for multiple elements.setAttribute
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
Remove Multiple DOM Elements
Use a loop to detach elements and then remove them all at once. ``` const elementsToRemove = docum...
Inject a Script into Document Head or Body Tags
You can inject js script into the document head dynamically like this : ``` const basicScript = do...