#htmx #html #frontend

Day 3: Targeting Elements

Welcome to Day 3.

By default, htmx swaps the content of the element that triggered the request. Element A sends request -> Server responds -> Element A content replaced.

Often, you want Button A to update Div B. We use hx-target.

Basic Targeting

Use a CSS selector.

<button hx-get="/news" hx-target="#news-feed">
    Load News
</button>

<div id="news-feed">
    <!-- Content lands here -->
</div>

Relative Targeting

Sometimes looking up IDs is tedious, especially in lists. Use closest or this.

closest

Look up the DOM tree.

<tr id="row-42">
    <td>John Doe</td>
    <td>
        <!-- Deletes the whole row found by closest tr -->
        <button hx-delete="/users/42" hx-target="closest tr">
            Delete
        </button>
    </td>
</tr>

this

Explicitly target the element itself (default behavior, but sometimes clarity helps).

<button hx-get="/update" hx-target="this">Update Me</button>

next and previous

Target adjacent elements.

<button hx-get="/details" hx-target="next .details">Show</button>
<div class="details"></div>

Challenge for Day 3

  1. Create a standard “To Do” list item.
  2. It has a “Delete” button.
  3. When clicked, the button sends a DELETE request.
  4. The entire list item (<li>) should be removed (replaced with empty response).
  5. Use extended CSS selectors.

Solution:

<ul>
  <li class="item">
    <span>Buy Milk</span>
    <button hx-delete="/todos/1" hx-target="closest li" hx-swap="outerHTML">
        X
    </button>
  </li>
</ul>

You can now shoot regular HTML straight into any div you want. Tomorrow: The Art of the Swap.