Replacing entire body using HTMX – Htmx

by
Alexei Petrov
html htmx

The Problem:

Consider the following code. Here, clicking the bomb icon will replace the entire body with a new one, but the class of the body element remains the same. The goal is to update the class of the body element to ‘bomb-animation’ when the body is replaced.

<body id="bomb-main" class="main-page">
  <div class="bomb"
       hx-trigger="click"
       hx-swap="outerHTML"
       hx-target="#bomb-main"
       hx-get="/boom">πŸ”«
  </div>
</body>

The request to /boom returns the following response:

<body id="bomb-main" class="bomb-animation">
  <h1>ka-boom</h1>
</body>

How can I ensure that the class of the body element is updated to ‘bomb-animation’ upon clicking the bomb icon?

The Solutions:

Solution 1: Use `hx-replace` instead of `hx-swap`

`hx-swap` replaces the contents of the target element with the response HTML, while `hx-replace` replaces the entire target element with the response HTML. In this case, we want to replace the entire `` element, so we should use `hx-replace` instead of `hx-swap`.

&lt;div class="bomb"
     hx-trigger="click"
     hx-replace="outerHTML"
     hx-target="#bomb-main"
     hx-get="/boom"&gt;&#128163;&lt;/div&gt;

This will correctly replace the entire `` element with the response HTML, including the `class` attribute.

Q&A

How to change the class of <body>?

β€”

htmx converts outerHTML to innerHTML swap value. Hence, it’s not possible to change class of the <body> element.

What is the issue?

β€”

htmx swaps outerHTML to innerHTML in the hx-swap method.

What does htmx documentation say about this?

β€”

Due to DOM limitations, it’s not possible to use outerHTML method on &lt;body&gt; element.

Video Explanation:

The following video, titled "Power Automate flow HTML Table Formatting in Email | Flows ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

This video is a step by step tutorial of how to create HTML table in Microsoft Power Automate and email the table data. We will use Power ...