JAVASCRIPT
Update Element Attributes and Text Content
Learn to dynamically modify an HTML element's attributes (e.g., `src`, `href`, `placeholder`) and its inner text content using JavaScript methods for interactive updates.
document.addEventListener('DOMContentLoaded', () => {
const myImage = document.getElementById('myImage');
const myParagraph = document.getElementById('myParagraph');
const myLink = document.getElementById('myLink');
if (myImage) {
// Change the image source and alt text
myImage.setAttribute('src', 'https://via.placeholder.com/150/FF0000/FFFFFF?text=New+Image');
myImage.setAttribute('alt', 'A new placeholder image in red');
console.log('Image attributes updated.');
}
if (myParagraph) {
// Update the text content of a paragraph
myParagraph.textContent = 'This paragraph now has updated content via JavaScript!';
console.log('Paragraph text content updated.');
}
if (myLink) {
// Update the href and target attributes of a link
myLink.setAttribute('href', 'https://www.example.com/new-page');
myLink.setAttribute('target', '_blank');
console.log('Link attributes updated.');
}
});
// Example HTML for context:
// <img id="myImage" src="https://via.placeholder.com/150" alt="Placeholder Image">
// <p id="myParagraph">Original paragraph content.</p>
// <a id="myLink" href="#">Original Link</a>
How it works: This snippet demonstrates how to modify an element's attributes and text content. The `setAttribute()` method is used to change or add any attribute, such as `src` and `alt` for an image, or `href` and `target` for a link. The `textContent` property is directly accessed to update the visible text inside an element, replacing its old content. These methods are essential for dynamically updating visual information or interactive elements on a web page.