JAVASCRIPT

Update DOM Element Attributes and CSS Styles

Learn to programmatically change HTML attributes like `src` or `href` and inline CSS styles for DOM elements using JavaScript for dynamic UIs.

<img id="my-image" src="initial-image.jpg" alt="A placeholder image" style="width: 100px; border: 1px solid gray;">
<a id="my-link" href="#initial" target="_blank">Visit Initial Link</a>

<script>
const myImage = document.getElementById('my-image');
const myLink = document.getElementById('my-link');

// Updating attributes
myImage.setAttribute('src', 'new-image.png'); // Changes the image source
myImage.setAttribute('alt', 'A new image description'); // Updates alt text
myLink.href = 'https://example.com'; // Changes the link URL
myLink.textContent = 'Visit Example.com'; // Changes the link text

// Updating inline styles
myImage.style.width = '250px';
myImage.style.height = 'auto';
myImage.style.borderColor = 'blue';
myImage.style.borderRadius = '5px';

console.log('Image attributes and styles updated.');
</script>
How it works: This snippet demonstrates how to modify both HTML attributes and inline CSS styles of existing DOM elements. Attributes like `src`, `alt`, or `href` can be changed using `setAttribute()` or directly via element properties (e.g., `myLink.href`). CSS styles are manipulated through the element's `style` object, where properties are typically camelCased (e.g., `backgroundColor` instead of `background-color`). This allows for dynamic visual and functional changes to elements.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs