Attribute Inheritance

Introduction

Most attributes in htmx are inherited: they apply to the element they are on as well as any children elements. This allows you to “hoist” attributes up the DOM to avoid code duplication. Consider the following htmx:

<button hx-delete="/account" hx-confirm="Are you sure?">
  Delete My Account
</button>
<button hx-put="/account" hx-confirm="Are you sure?">
  Update My Account
</button>

Here we have a duplicate hx-confirm attribute. We can hoist this attribute to a parent element:

<div hx-confirm="Are you sure?">
    <button hx-delete="/account">
      Delete My Account
    </button>
    <button hx-put="/account">
      Update My Account
    </button>
</div>

This hx-confirm attribute will now apply to all htmx-powered elements within it.

Sometimes you wish to undo this inheritance. Consider if we had a cancel button to this group, but didn’t want it to be confirmed.

We could add an unset directive on it like so:

<div hx-confirm="Are you sure?">
    <button hx-delete="/account">
      Delete My Account
    </button>
    <button hx-put="/account">
      Update My Account
    </button>
    <button hx-confirm="unset" hx-get="/">
      Cancel
    </button>
</div>

The top two buttons would then show a confirm dialog, but the bottom cancel button would not.