JAVASCRIPT
Update Text Content and Attributes of Existing Elements
Master updating the visible text content and modifying attributes like 'src' or 'href' of an existing HTML element using JavaScript's powerful DOM APIs.
const myParagraph = document.getElementById('myParagraph');
const myImage = document.getElementById('myImage');
const myLink = document.getElementById('myLink');
// Update text content
if (myParagraph) {
myParagraph.textContent = 'The text content has been updated dynamically!';
}
// Update attributes
if (myImage) {
myImage.setAttribute('src', 'https://picsum.photos/200/300?random=1');
myImage.alt = 'A new random image from Lorem Picsum';
}
if (myLink) {
myLink.href = 'https://www.example.com/new-page';
myLink.textContent = 'Visit New Example Page';
myLink.target = '_blank'; // Open in new tab
}
How it works: This code illustrates how to modify existing elements in the DOM. It uses `textContent` to change the visible text inside an element. For attributes, it shows both `setAttribute()` for general attribute manipulation and direct dot notation (e.g., `myImage.src`, `myLink.href`) for common attributes, providing flexible ways to update element properties.