To disable and re-enable an HTML <button> (or form control) in JavaScript, set its boolean disabled property (button.disabled = true to disable and button.disabled = false to re-enable)—and for accessibility and visual state, also pair it with aria-disabled when needed (or when disabling a non-button interactive element like an <a> tag, since <button>'s native disabled attribute already blocks clicks, form submission, and keyboard activation). Always guard for null elements and avoid toggling disabled inside tight loops without clear state tracking.


1. Toggling button.disabled Safely with Defensive Validation

Use button.disabled = true and button.disabled = false directly on a validated HTMLButtonElement (or element supporting .disabled), keeping state transitions explicit and guarded:

// Set the native `disabled` state on a button element safely
function setButtonDisabled(button, isDisabled) {
  if (!(button instanceof Element) || typeof button.disabled !== "boolean") {
    throw new TypeError("Expected button to be a DOM element with a boolean disabled property.");
  }
  if (typeof isDisabled !== "boolean") {
    throw new TypeError("Expected isDisabled to be a boolean.");
  }

  try {
    button.disabled = isDisabled;
    if (isDisabled) {
      button.setAttribute("aria-disabled", "true");
    } else {
      button.removeAttribute("aria-disabled");
    }
    return button.disabled;
  } catch (error) {
    throw new Error(`Failed to update button disabled state: ${error.message}`);
  }
}

// Example usage:
try {
  const submitBtn = document.querySelector("#submit-btn");
  if (submitBtn) {
    setButtonDisabled(submitBtn, true);  // Disable before async work
    setButtonDisabled(submitBtn, false); // Re-enable after completion
  }
} catch (error) {
  console.error(`${error.name}: ${error.message}`);
}
  • Use button.disabled = true rather than .setAttribute("disabled", "disabled"): Setting the boolean property directly is cleaner, faster, and reflects live DOM state reliably.
  • Native disabled blocks click and Enter/Space events automatically: Browsers prevent user interaction and form submission while disabled is true.

2. Disabling Buttons During Asynchronous Operations (try / finally)

When disabling a button while a fetch() or async task runs, always re-enable it in a finally block so an API failure or network error never leaves the user stuck with a permanently disabled button:

// Run an async action while keeping a button disabled until settled
async function runWithDisabledButton(button, asyncAction) {
  if (!(button instanceof Element) || typeof button.disabled !== "boolean") {
    throw new TypeError("Expected button to be a DOM element with a boolean disabled property.");
  }
  if (typeof asyncAction !== "function") {
    throw new TypeError("Expected asyncAction to be a function.");
  }

  button.disabled = true;
  button.setAttribute("aria-disabled", "true");

  try {
    return await asyncAction();
  } finally {
    button.disabled = false;
    button.removeAttribute("aria-disabled");
  }
}

// Example usage:
// const saveBtn = document.querySelector("#save-btn");
// await runWithDisabledButton(saveBtn, async () => {
//   // perform async request
// });
  • finally guarantees re-enabling on both success and failure: Prevents deadlocked submit buttons after failed requests.
  • Consider updating visible button text/label carefully: If you swap "Save" to "Saving...", restore the original label in finally too.

3. Styling Disabled Buttons and Non-Button Elements (<a> / <div>)

Style disabled states using the CSS :disabled pseudo-class (button:disabled { opacity: 0.55; cursor: not-allowed; }), and note that <a> links do not support the native disabled attribute—for links, use aria-disabled="true", prevent default navigation in the click handler when disabled, and style [aria-disabled="true"]:

// Guard a link or custom action element that uses `aria-disabled="true"`
function bindAriaDisabledLink(linkElement, onAllowedClick) {
  if (!(linkElement instanceof Element)) {
    throw new TypeError("Expected linkElement to be a DOM Element.");
  }
  if (typeof onAllowedClick !== "function") {
    throw new TypeError("Expected onAllowedClick to be a function.");
  }

  const handleClick = (event) => {
    try {
      const isAriaDisabled = linkElement.getAttribute("aria-disabled") === "true";
      if (isAriaDisabled) {
        event.preventDefault();
        event.stopPropagation();
        return;
      }
      onAllowedClick(event);
    } catch (error) {
      console.error(`Link click handler error: ${error.message}`);
    }
  };

  linkElement.addEventListener("click", handleClick);
  return () => linkElement.removeEventListener("click", handleClick);
}

// Example usage:
// const exportLink = document.querySelector("#export-link");
// const cleanupLink = bindAriaDisabledLink(exportLink, () => console.log("Exporting..."));
  • Prefer real <button type="button"> / <button type="submit"> elements for actions: Native form semantics and keyboard accessibility come built in.
  • Avoid relying solely on pointer-events: none without accessibility cues: Visually dimming without communicating state to assistive tech or blocking keyboard triggers can confuse users.