← Back to all snippets
JAVASCRIPT

Modify Element Attributes and CSS Styles

Discover how to programmatically change HTML element attributes such as `src` or `href`, and manipulate inline CSS styles like `color` or `fontSize` using JavaScript DOM properties.

const imageElement = document.getElementById('myImage');
if (imageElement) {
  // Change attributes
  imageElement.setAttribute('src', 'https://via.placeholder.com/150/FF0000/FFFFFF?text=NewImage');
  imageElement.setAttribute('alt', 'A new placeholder image');
  
  // Change inline styles
  imageElement.style.width = '150px';
  imageElement.style.height = '150px';
  imageElement.style.border = '3px solid #007bff';
  imageElement.style.borderRadius = '8px';
}

const myButton = document.querySelector('.action-button');
if (myButton) {
  // Add/remove/toggle CSS classes
  myButton.classList.add('active');
  myButton.classList.remove('inactive');
  
  // Directly set style properties
  myButton.style.backgroundColor = 'purple';
  myButton.style.color = 'white';
  myButton.textContent = 'Activated!';
}
How it works: This snippet shows how to modify HTML element attributes and inline CSS styles. `setAttribute()` is used to change standard HTML attributes like `src` and `alt`. Inline CSS styles are directly set using the `element.style` property (e.g., `element.style.width`). Additionally, `classList.add()`, `classList.remove()`, and `classList.toggle()` are demonstrated for managing CSS classes, which is often a more maintainable approach for styling than direct inline style manipulation.

Need help integrating this into your project?

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

Hire DigitalCodeLabs