← Back to all snippets
JAVASCRIPT

Update Element Attributes and Inline Styles

Discover how to programmatically change an HTML element's attributes (like `class`, `id`, `src`) and inline CSS styles using pure JavaScript DOM manipulation.

function updateElementProperties(selector, attributes = {}, styles = {}) {
    const element = typeof selector === 'string' ? document.querySelector(selector) : selector;
    if (!element) {
        console.error(`Element with selector '${selector}' not found.`);
        return false;
    }

    // Update attributes
    for (const key in attributes) {
        element.setAttribute(key, attributes[key]);
    }

    // Update inline styles
    for (const key in styles) {
        // Convert camelCase to kebab-case for CSS properties if needed, though JS style object usually handles camelCase
        element.style[key] = styles[key];
    }
    return true;
}

// Example Usage:
// <img id="myImage" src="old.jpg" alt="Old Image" class="thumbnail">
// <p class="message">Hello World</p>

// updateElementProperties('#myImage', { src: 'new.jpg', alt: 'New Image', 'data-status': 'updated' });
// updateElementProperties('.message', { class: 'highlighted-message' }, { color: 'red', fontSize: '18px' });
// updateElementProperties(document.getElementById('myImage'), { width: '100px' }, { border: '2px solid blue' });
How it works: This snippet provides a flexible function to update both HTML attributes and inline CSS styles of a specific DOM element. It accepts a CSS selector string or an element object, making it versatile for targeting elements and applying dynamic changes to their appearance or behavior, such as changing an image source or text color.

Need help integrating this into your project?

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

Hire DigitalCodeLabs