JAVASCRIPT

Manipulating General HTML Element Attributes

Discover how to programmatically get, set, and remove any standard or custom HTML attribute on a DOM element using JavaScript, enhancing dynamic element control.

function setElementAttribute(elementId, attributeName, attributeValue) {
  const element = document.getElementById(elementId);
  if (element) {
    element.setAttribute(attributeName, attributeValue);
    return true;
  }
  return false;
}

function getElementAttribute(elementId, attributeName) {
  const element = document.getElementById(elementId);
  return element ? element.getAttribute(attributeName) : null;
}

function removeElementAttribute(elementId, attributeName) {
  const element = document.getElementById(elementId);
  if (element) {
    element.removeAttribute(attributeName);
    return true;
  }
  return false;
}
How it works: These functions demonstrate how to manage generic HTML attributes on an element. `setAttribute()` adds or updates an attribute (e.g., `src`, `href`, `title`), `getAttribute()` retrieves its current value, and `removeAttribute()` deletes it entirely. This is essential for dynamically controlling element behavior and presentation, such as enabling/disabling inputs or changing image sources.

Need help integrating this into your project?

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

Hire DigitalCodeLabs