The response-targets Extension

This extension allows you to specify different target elements to be swapped when different HTTP response codes are received.

It uses attribute names in a form of hx-target-[CODE] where [CODE] is a numeric HTTP response code with the optional wildcard character at its end. You can also use hx-target-error, which handles both 4xx and 5xx response codes.

The value of each attribute can be:

#Install

<script src="https://unpkg.com/htmx.org/dist/ext/response-targets.js"></script>

#Configure (optional)

#Usage

Here is an example that targets a div for normal (200) response but another div for 404 (not found) response, and yet another for all 5xx response codes:

<div hx-ext="response-targets">
    <div id="response-div"></div>
    <button hx-post="/register"
            hx-target="#response-div"
            hx-target-5*="#serious-errors"
            hx-target-404="#not-found">
        Register!
    </button>
    <div id="serious-errors"></div>
    <div id="not-found"></div>
</div>

Sometimes you may not want to handle 5xx and 4xx errors separately, in which case you can use hx-target-error:

<div hx-ext="response-targets">
    <div id="response-div"></div>
    <button hx-post="/register"
            hx-target="#response-div"
            hx-target-error="#any-errors">
        Register!
    </button>
    <div id="any-errors"></div>
</div>

2xx codes will be handled as in the previous example. However, when the response code is 5xx or 4xx, the response from /register will replace the contents of the div with the id any-errors.

#Wildcard resolution

When status response code does not match existing hx-target-[CODE] attribute name then its numeric part expressed as a string is trimmed with last character being replaced with the asterisk (*). This lookup process continues until the attribute is found or there are no more digits.

For example, if a browser receives 404 error code, the following attribute names will be looked up (in the given order):

If you are using tools that do not support asterisks in HTML attributes, you may instead use the x character, e.g., hx-target-4xx.

#Notes

#See also