JAVASCRIPT
Dynamically Update Standard Attributes of an Element
Learn to programmatically change standard HTML attributes like `src` for images or `href` for links using JavaScript's `setAttribute()` method, ensuring dynamic content.
const myImage = document.getElementById('dynamicImage');
const myLink = document.getElementById('dynamicLink');
if (myImage) {
myImage.setAttribute('src', 'https://via.placeholder.com/150/FF0000/FFFFFF?text=New+Image');
myImage.setAttribute('alt', 'A dynamically loaded red placeholder image');
myImage.setAttribute('title', 'Click to see a new image');
}
if (myLink) {
myLink.setAttribute('href', 'https://www.google.com/search?q=javascript+dom');
myLink.setAttribute('target', '_blank');
myLink.textContent = 'Search JavaScript DOM on Google'; // Update link text as well
}
// HTML Structure (example):
// <img id="dynamicImage" src="https://via.placeholder.com/150" alt="Placeholder Image">
// <a id="dynamicLink" href="#">My Link</a>
How it works: This code snippet illustrates how to dynamically update standard HTML attributes of elements using JavaScript's `setAttribute()` method. It targets an <img> element to change its `src`, `alt`, and `title` attributes, and an <a> element to modify its `href` and `target`. This is crucial for updating interactive content like image galleries, navigation links, or any element whose behavior or appearance is controlled by its attributes.