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 requesthx-target
indicates the element to replace with the responsehx-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 elementouterHTML
- Replace the entire target element with the responsebeforebegin
- Insert the response before the target elementafterbegin
- Insert the response before the first child of the target elementbeforeend
- Insert the response after the last child of the target elementafterend
- Insert the response after the target elementdelete
- Deletes the target element regardless of the responsenone
- 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.