htmx Tutorial · User Feedback · Lesson 13 of 30
Picking Part of a Response: hx-select
Use only part of a server response with hx-select, useful when a URL returns a full page.
hx-select
Sometimes the server returns more HTML than you need, for example a whole page. hx-select takes a CSS selector
and keeps only the matching element from the response:
<button hx-get="/about" hx-select="#team" hx-target="#here">Show only the team section</button>
<div id="here"></div>
<!-- The pretend server: on a real site this part is your backend (Python, PHP, Node, Go...) -->
<script>
// The server returns a whole page; hx-select keeps only #team.
server.get("/about", () => `<html><body>
<header>Big site header</header>
<section id="team"><h3>Our team</h3><ul><li>Ada</li><li>Grace</li></ul></section>
<footer>Footer, links, scripts...</footer></body></html>`);
</script>
This lets htmx work with existing pages without changing the server at all. The trade-off: the server still renders and sends the full page, so dedicated fragments are faster when you control the backend.
hx-select-oob
hx-select-oob="#count" picks extra elements from the response and swaps them into the page elements with the same
id, in addition to the main swap:
<p>Unread messages: <strong id="count">3</strong></p>
<button hx-get="/inbox" hx-select="#messages" hx-select-oob="#count" hx-target="#box">Open inbox</button>
<div id="box"></div>
<!-- The pretend server: on a real site this part is your backend (Python, PHP, Node, Go...) -->
<script>
server.get("/inbox", () => `<div id="messages"><p>Hi from Ada</p><p>Lunch?</p><p>Build passed</p></div>
<strong id="count">0</strong>`);
</script>
Test yourself
A URL returns a full HTML page, but you only want its #results element. Which attribute helps?
hx-select="#results"hx-target="#results"hx-swap="#results"hx-include="#results"
Show answer
Answer: hx-select="#results"
hx-select chooses what to take from the response; hx-target chooses where to put it.