hx-select
When the server returns a broad html response, we can use hx-select
to select a part of the response and replace the target element with it.
For example, consider the following html
<body>
<div id="main-info">
</div>
<div>
Some content here
</div>
<button hx-get="/get-update" hx-target="#main-info" hx-select="#main-info"> update </button>
</body>
and we get a response from /get-update
endpoint like this
<div id="main-info">
Main information
<p>This is main info</p>
</div>
<div id="extra-info">
<p>Additional info 1</p>
<p>Additional info 2</p>
</div>
The hx-select
will only select the element with id main-info
and replace the target element #main-info
with it. so the result will be
<body>
<div id="main-info">
Main information
<p>This is main info</p>
</div>
<div>
Some content here
</div>
<button hx-get="/get-update" hx-target="#main-info" hx-select="#main-info"> update </button>
</body>
hx-select-oob
We can also replace elements outside the target element using hx-select-oob
.
hx-select-oob
is a comma seperated list of selectors. HTMX will select the elements matching the selectors and replace them with the response.
For example, consider the following html
<body>
<div id="main-info">
</div>
<div>
Some content here
</div>
<div id="extra-info">
</div>
<button hx-get="/get-update" hx-target="#main-info" hx-select="#main-info" hx-select-oob="#extra-info"> update </button>
</body>
and we get a response from /get-update
endpoint like this
<div id="main-info">
Main information
<p>This is main info</p>
</div>
<div id="extra-info">
<p>Additional info 1</p>
<p>Additional info 2</p>
</div>
<div id="extra-info-2">
<p>Additional info 3</p>
<p>Additional info 4</p>
</div>
<span>some extra content</span>
The hx-select
will only select the element with id main-info
and replace the target element #main-info
with it. so the result will be
<body>
<div id="main-info">
Main information
<p>This is main info</p>
</div>
<div>
Some content here
</div>
<div id="extra-info">
<p>Additional info 1</p>
<p>Additional info 2</p>
</div>
<button hx-get="/get-update" hx-target="#main-info" hx-select="#main-info" hx-select-oob="#extra-info"> update </button>
</body>
These selectors are very useful if the response is elaborate and want to select the parts from the response and replace them in the page.