← Back to all snippets
JAVASCRIPT

Modify Element Attributes and Inline Styles

Discover how to dynamically change HTML attributes (like 'src', 'href', 'data-*') and inline CSS styles of any DOM element using JavaScript.

const myImage = document.getElementById('myImage');
myImage.src = 'new-image.jpg';
myImage.alt = 'A new descriptive alt text';
myImage.setAttribute('data-category', 'nature');
myImage.style.width = '200px';
myImage.style.border = '2px solid blue';
How it works: This code snippet illustrates how to directly manipulate an element's standard attributes (like 'src' and 'alt') and custom data attributes using 'setAttribute()'. It also shows how to apply inline CSS styles directly via the 'style' property, allowing for dynamic visual changes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs