Use htmx.swap() to run the swap lifecycle without issuing a request.

await htmx.swap({ text: '<p>Done</p>', target: '#result' })

htmx swaps the content into #result with the default swap style.

For requests, use htmx.ajax().

Syntax

htmx.swap(ctx)

Set the content, target, and swap style in the context:

await htmx.swap({ text: '<p>Done</p>', target: '#result', swap: 'outerHTML transition:true' })

Context

text

The HTML string to swap.

await htmx.swap({ text: '<strong>Saved</strong>', target: '#status' })

target

The target element or selector. It defaults to document.body.

await htmx.swap({ text: 'Saved', target: document.querySelector('#status') })
await htmx.swap({ text: 'Saved', target: '#status' })

swap

A serialized hx-swap value.

await htmx.swap({ text: 'Saved', target: '#status', swap: 'innerHTML transition:true settle:100ms' })

It defaults to htmx.config.defaultSwap.

Other Fields

FieldDescription
sourceElementElement used for relative selectors and swap events
selectContent selected from text
selectOOBOut-of-band content selected from text
transitionWhether to use a view transition

Set the Source

Set sourceElement when a target or swap modifier uses a relative selector:

let button = document.querySelector('#save') await htmx.swap({ text: 'Saved', target: 'closest .result', sourceElement: button })

The source element also receives swap lifecycle events.

Select Response Content

Use select to swap part of the content:

await htmx.swap({ text: '<p id="message">Saved</p><p>Ignored</p>', target: '#status', select: '#message' })

Use selectOOB for out-of-band content.

Events

htmx.swap() fires:

Swap events fire on sourceElement. Settle events fire on each swap target.

Return Value

htmx.swap() returns a Promise that resolves after the swap finishes.

await htmx.swap({ text: 'Saved', target: '#result' }) console.log('Swap complete')

Notes

  • htmx.swap() processes main, out-of-band, and <hx-partial> content.
  • htmx.swap() does not issue a request.

See Also