HTMX - Attribute Inheritance



HTMX attributes are inherited in most cases, if you apply any attribute on the parent element then the child elements will auto-inherit the behavior of that attribute in most of the cases(Where it feels required).

This attribute inheritance allows you to hoist attributes up to the DOM so that code duplication can be avoided. As you can see in the code example below,

Avoid Code Duplication using Attribute Inheritance

Here we will have two elements and one attribute will be common that is hx-confirm to show a confirm dialog to the user.

<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>

So, we can wrap both the elements within a parent element and use the hx-confirm attribute on the parent.

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

If you need to add one or more child elements in that div where you do not want that child element to inherit the parent's behavior. Then simply you can add unset value on hx-confirm attribute.

<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>

Disable Attribute Inheritance

Attribute inheritance can be disabled on element and attribute basis individually by using hx-disinherit attribute.

To disable attribute inheritance entirely you need to set htmx.config.disableInheritance configuration variable to true. This will disable the inheritance and let you use the inheritance explicitly by using hx-inherit attribute.

Advertisements