JAVASCRIPT

Updating Element Attributes and Inline Styles

Discover how to dynamically change HTML attributes like 'src' or 'alt', and apply inline CSS styles to any DOM element using JavaScript for interactive web pages.

// Get a reference to an existing image element
const myImage = document.getElementById('myImage'); // Assuming <img id="myImage" src="initial.jpg">

if (myImage) {
  // Update the 'src' attribute
  myImage.setAttribute('src', 'new-image.jpg');
  // Update the 'alt' attribute
  myImage.setAttribute('alt', 'A beautiful new image');

  // Change inline CSS styles
  myImage.style.width = '300px';
  myImage.style.border = '2px solid blue';
  myImage.style.borderRadius = '8px';
} else {
  console.error('Image element with ID "myImage" not found.');
}
How it works: This code illustrates how to modify an existing DOM element's attributes and inline styles. `setAttribute()` is used to change standard HTML attributes like `src` and `alt` on an image. Direct manipulation of the `style` property allows setting CSS properties, such as `width`, `border`, and `borderRadius`, directly on the element.

Need help integrating this into your project?

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

Hire DigitalCodeLabs