JAVASCRIPT
Dynamically Change Element Styles and Attributes
Explore how to dynamically modify an element's inline CSS styles and various HTML attributes (like 'src', 'href', 'disabled') using JavaScript DOM methods for interactive web pages.
function updateElementProperties(elementId) {
const element = document.getElementById(elementId);
if (!element) {
console.error('Element not found.');
return;
}
// Change inline CSS styles directly using the style property
element.style.color = 'blue';
element.style.fontSize = '20px';
element.style.border = '1px solid red';
// Change HTML attributes using setAttribute or specific properties
if (element.tagName === 'IMG') {
element.setAttribute('src', 'https://via.placeholder.com/150/0000FF/FFFFFF?text=New+Image'); // Example image src
element.setAttribute('alt', 'A Dynamically Updated Image');
} else if (element.tagName === 'A') {
element.setAttribute('href', 'https://www.example.com/new-page');
element.setAttribute('target', '_blank');
} else {
element.setAttribute('data-status', 'updated'); // Set a custom attribute
element.toggleAttribute('disabled', true); // Add/remove boolean attribute (true adds, false removes)
element.textContent = 'Content has been updated and styled!';
}
}
// Example Usage:
// <p id="myParagraph">This is a paragraph.</p>
// updateElementProperties('myParagraph');
// <img id="myImage" src="old-image.jpg" alt="Old image">
// updateElementProperties('myImage');
How it works: This snippet illustrates how to dynamically modify an element's inline CSS styles using the `style` property, allowing granular control over visual presentation. It also demonstrates how to change various HTML attributes using `setAttribute` (e.g., updating an image source or link URL) and how to manage boolean attributes like `disabled` with `toggleAttribute`. This is crucial for creating highly interactive and responsive user interfaces based on application logic.