JAVASCRIPT
Modifying DOM Element Content and Attributes
Discover how to update the text content and change attributes of existing HTML elements using JavaScript, enabling dynamic content updates and styling.
function updateElementContentAndAttributes(elementId, newText, newAttributes = {}) {
const element = document.getElementById(elementId);
if (!element) {
console.error(`Element with ID '${elementId}' not found.`);
return;
}
element.textContent = newText;
for (const key in newAttributes) {
if (newAttributes.hasOwnProperty(key)) {
element.setAttribute(key, newAttributes[key]);
}
}
}
// Example usage:
// <h1 id="myHeading" data-original="Hello">Initial Heading</h1>
// updateElementContentAndAttributes('myHeading', 'Updated Heading Text', { 'data-modified': 'true', class: 'highlight' });
// <img id="myImage" src="old.jpg" alt="Old image">
// updateElementContentAndAttributes('myImage', '', { src: 'new.jpg', alt: 'New image', width: '200' });
How it works: This snippet demonstrates how to modify both the visible text content and arbitrary HTML attributes of an existing DOM element. It's crucial for reacting to user input, application state changes, or displaying updated data on the web page.