JAVASCRIPT

Update Standard Element Attributes Programmatically

Discover how to dynamically get and set common HTML attributes like `src`, `href`, or `id` on any DOM element, enabling responsive changes to element behavior or appearance.

function updateElementAttribute(elementId, attributeName, attributeValue) {
  const element = document.getElementById(elementId);
  if (element) {
    element.setAttribute(attributeName, attributeValue);
    console.log(`Attribute '${attributeName}' on element ID '${elementId}' updated to '${attributeValue}'.`);
  } else {
    console.error(`Element with ID '${elementId}' not found.`);
  }
}

function getElementAttribute(elementId, attributeName) {
  const element = document.getElementById(elementId);
  if (element) {
    const value = element.getAttribute(attributeName);
    console.log(`Attribute '${attributeName}' of element ID '${elementId}' is: ${value}`);
    return value;
  } else {
    console.error(`Element with ID '${elementId}' not found.`);
    return null;
  }
}

// Usage example:
// <img id="myImage" src="old-image.jpg" alt="Old Image">
// <a id="myLink" href="#old">Old Link</a>
// updateElementAttribute('myImage', 'src', 'new-image.png');
// updateElementAttribute('myImage', 'alt', 'New Image Description');
// getElementAttribute('myLink', 'href'); // Returns "#old"
How it works: This snippet demonstrates how to programmatically read and modify standard HTML attributes of an element. The `setAttribute` function is crucial for dynamically changing an element's behavior, such as updating an image source or a link's destination, while `getAttribute` allows retrieval of current attribute values.

Need help integrating this into your project?

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

Hire DigitalCodeLabs