← Back to all snippets
JAVASCRIPT

Modify DOM Element Attributes & Styles

Discover how to programmatically change HTML attributes such as 'src', 'href', or 'class', and apply inline CSS styles to any selected DOM element using JavaScript for dynamic UI updates.

function updateElementProperties(elementId, newAttributes = {}, newStyles = {}) {
  const element = document.getElementById(elementId);
  if (!element) {
    console.error(`Element with ID '${elementId}' not found.`);
    return;
  }

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

  // Update styles
  for (const prop in newStyles) {
    if (newStyles.hasOwnProperty(prop)) {
      element.style[prop] = newStyles[prop];
    }
  }
}

// Example usage:
// <img id="myImage" src="old-image.jpg" alt="Old Image">
// <p id="myText" style="color: black;">Some text here.</p>

updateElementProperties('myImage', {
  src: 'new-image.png',
  alt: 'New Image description',
  width: '200'
});

updateElementProperties('myText', { class: 'highlighted' }, {
  color: 'red',
  fontWeight: 'bold',
  fontSize: '18px'
});

// Add a class to an existing class list
document.getElementById('myText').classList.add('active');
// Remove a class
document.getElementById('myText').classList.remove('highlighted');
// Toggle a class
document.getElementById('myText').classList.toggle('visible');
How it works: This snippet demonstrates how to dynamically update both HTML attributes and inline CSS styles of a specific DOM element. It uses `element.setAttribute()` for changing attributes like `src` or `alt`, and `element.style.propertyName` for applying CSS properties (note the camelCase for CSS properties like `fontWeight`). Additionally, it shows the use of `classList.add()`, `classList.remove()`, and `classList.toggle()` for managing CSS classes, which is often preferred over inline styles for better separation of concerns.

Need help integrating this into your project?

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

Hire DigitalCodeLabs