The main attraction of HTMX is that it allows us to asynchronously swap the content of an element with server response using hx-swap and hx-target attribute with minimal effort and with less / no javascript.

For an html contnet like this

<html>
    <head>
        <title>HTMX - Using htmx hx-target and hx-swap attribute</title>
    </head>
    <body>
        <div id="content">
            <p>Content will be replaced here</p>
        </div>
        <button id="btn" hx-get="/get-content" hx-target="#content" hx-swap="outerHTML">Click Me</button>
    </body>
</html>

Let’s look at the button attributes

  • hx-get indicates the url to send get request
  • hx-target indicates the element to replace with the response
  • hx-swap indicates the way to replace the content. In this case, we are replacing the whole content of the element with the response.

hx-swap can take the following values

  • innerHTML - Replace the inner html of the target element
  • outerHTML - Replace the entire target element with the response
  • beforebegin - Insert the response before the target element
  • afterbegin - Insert the response before the first child of the target element
  • beforeend - Insert the response after the last child of the target element
  • afterend - Insert the response after the target element
  • delete - Deletes the target element regardless of the response
  • none - Does not append content from response (out of band items will still be processed).

Suppose the server response from /get-content is the following html

<div id="content">
    <h1>HTMX - Using htmx hx-target and hx-swap attribute</h1>
    <p>HTMX allows us to asynchronously swap the content of an element with server response using hx-swap and hx-target attribute.</p>
</div>

The htmx will replace the content of the hx-target - #content div with the response and the final html will be

<html>
    <head>
        <title>HTMX - Using htmx hx-target and hx-swap attribute</title>
    </head>
    <body>
        <div id="content">
            <h1>HTMX - Using htmx hx-target and hx-swap attribute</h1>
            <p>HTMX allows us to asynchronously swap the content of an element with server response using hx-swap and hx-target attribute.</p>
        </div>
        <button id="btn" hx-get="/get-content" hx-target="#content" hx-swap="outerHTML">Click Me</button>
    </body>
</html>

For most usecases, we can use this approach to update the UI with the data from server.