Javascript API
While it is not a focus of the library, htmx does provide a small API of helper methods, intended mainly for extension development or for working with events.
The hyperscript project is intended to provide more extensive scripting support for htmx-based applications.
Core Methods
Method - htmx.ajax()
Issues an htmx-style AJAX request. This method returns a Promise, so a callback can be executed after the content has been inserted into the DOM.
Parameters
verb- ‘GET’, ‘POST’, etc.path- the URL path to make the AJAX requestelement- the element to target (defaults to thebody)
or
verb- ‘GET’, ‘POST’, etc.path- the URL path to make the AJAX requestselector- a selector for the target
or
verb- ‘GET’, ‘POST’, etc.path- the URL path to make the AJAX requestcontext- a context object that contains any of the following:source- the source element of the requestevent- an event that “triggered” the requesthandler- a callback that will handle the response HTMLtarget- the target to swap the response intoswap- how the response will be swapped in relative to the targetvalues- values to submit with the requestheaders- headers to submit with the requestselect- allows you to select the content you want swapped from a responseselectOOB- allows you to select content for out-of-band swaps from a response
Example
// issue a GET to /example and put the response HTML into #myDiv
htmx.ajax('GET', '/example', '#myDiv')
// issue a GET to /example and replace #myDiv with the response
htmx.ajax('GET', '/example', {target:'#myDiv', swap:'outerHTML'})
// execute some code after the content has been inserted into the DOM
htmx.ajax('GET', '/example', '#myDiv').then(() => {
console.log('Content inserted successfully!');
});
Method - htmx.find()
Finds an element matching the selector. Supports extended CSS selectors like next, previous, closest, etc.
Parameters
selector- the selector to match
or
elt- the root element to find the matching element in, inclusiveselector- the selector to match
Example
// find div with id my-div
var div = htmx.find("#my-div")
// find next div after the current element
var nextDiv = htmx.find(div, "next div")
// find closest parent form
var form = htmx.find(div, "closest form")
Method - htmx.findAll()
Finds all elements matching the selector. Supports extended CSS selectors.
Parameters
selector- the selector to match
or
elt- the root element to find the matching elements in, inclusiveselector- the selector to match
Example
// find all divs
var allDivs = htmx.findAll("div")
// find all paragraphs within a given div
var allParagraphsInMyDiv = htmx.findAll(htmx.find("#my-div"), "p")
Method - htmx.on()
Adds an event listener to an element or the document.
Parameters
eventName- the event name to add the listener forlistener- the listener to add
or
target- the element to add the listener toeventName- the event name to add the listener forlistener- the listener to add
Example
// add a click listener to the document
htmx.on("click", function(evt){ console.log(evt); });
// add a click listener to the given div
htmx.on("#my-div", "click", function(evt){ console.log(evt); });
// listen for htmx events
htmx.on("htmx:after:swap", function(evt){
console.log("Content swapped!", evt.detail);
});
Method - htmx.onLoad()
Adds a callback for the htmx:after:init event. This can be used to process new content, for example initializing the content with a javascript library.
Parameters
callback(elt)- the callback to call on newly loaded content
Example
htmx.onLoad(function(elt){
MyLibrary.init(elt);
})
Method - htmx.process()
Processes new content, enabling htmx behavior. This can be useful if you have content that is added to the DOM outside of the normal htmx request cycle but still want htmx attributes to work.
Parameters
elt- element to process
Example
document.body.innerHTML = "<div hx-get='/example'>Get it!</div>"
// process the newly added content
htmx.process(document.body);
Method - htmx.swap()
Performs swapping of HTML content into the DOM. This is an internal method primarily used by htmx itself and extension developers.
Note: For most use cases, htmx.ajax() is the recommended approach for making requests and swapping content, as it handles the full request lifecycle.
Parameters
ctx- a context object containing:text(required) - the HTML content to swap as a stringtarget- the target element to swap into (defaults todocument.body)swap- swap style string (e.g.,'innerHTML','outerHTML', etc.)select- CSS selector to extract content from responseselectOOB- selector for out-of-band swapssourceElement- the element that triggered the swaptransition- boolean, whether to use view transitions
Example
// Swap content into an element
htmx.swap({
text: "<div>Swapped!</div>",
target: document.querySelector("#output"),
swap: 'innerHTML'
});
// For most cases, use htmx.ajax() instead:
htmx.ajax('GET', '/example', {
target: '#output',
swap: 'innerHTML'
});
Method - htmx.takeClass()
Takes the given class from its siblings (or elements within a container), so that among them, only the given element will have the class.
Parameters
elt- the element that will take the classclass- the class to takecontainer- (optional) the container to search within (defaults to element’s parent)
Example
// takes the selected class from tab2's siblings
htmx.takeClass(htmx.find("#tab2"), "selected");
// takes the active class from all buttons in the container
htmx.takeClass(htmx.find("#tab2"), "active", htmx.find("#button-group"));
Method - htmx.trigger()
Triggers a given event on an element.
Parameters
elt- the element to trigger the event onname- the name of the event to triggerdetail- details for the event
Example
// triggers the myEvent event on #tab2 with the answer 42
htmx.trigger("#tab2", "myEvent", {answer:42});
Utility Methods
Method - htmx.forEvent()
Returns a promise that resolves when the specified event fires. Useful for waiting for specific htmx lifecycle events.
Parameters
eventName- the event name to wait fortimeout- (optional) timeout in milliseconds (default: no timeout)
Example
// wait for a swap to complete
await htmx.forEvent("htmx:after:swap");
console.log("Swap completed!");
// wait for event with timeout
await htmx.forEvent("htmx:after:swap", 5000);
Method - htmx.timeout()
Returns a promise that resolves after the specified time.
Parameters
ms- time in milliseconds to wait
Example
// wait for 1 second
await htmx.timeout(1000);
console.log("1 second has passed");
Method - htmx.parseInterval()
Parses an interval string consistent with the way htmx does. Useful for extensions that have timing-related attributes.
Parameters
str- timing string (e.g., “100ms”, “2s”)
Example
// returns 3000
var milliseconds = htmx.parseInterval("3s");
// returns 500
var milliseconds = htmx.parseInterval("500ms");
Extension Methods
Method - htmx.registerExtension()
Registers a new htmx extension.
Parameters
name- the extension nameext- the extension definition
Example
// defines a simple extension that logs events
htmx.registerExtension("event-logger", {
init: (api) => {
// Store API reference if needed
},
htmx_before_request: (elt, detail) => {
console.log("Request starting on", elt);
},
htmx_after_swap: (elt, detail) => {
console.log("Content swapped!");
}
});
Configuration
Property - htmx.config
A property holding the configuration htmx uses at runtime.
Note that using a meta tag is the preferred mechanism for setting these properties.
Properties
logAll- boolean: if true, htmx will log all events for debugging (default:false)prefix- string: custom prefix for htmx attributes (default:"")transitions- boolean: whether to use view transitions when swapping (default:false)history- object: whether to enable history support, supports the valuestrue,falseor"reload"(default:true)mode- string: the fetch mode for AJAX requests (default:'same-origin')defaultSwap- string: default swap style (default:'innerHTML')indicatorClass- string: class for indicators (default:'htmx-indicator')requestClass- string: class for triggering elements during request (default:'htmx-request')includeIndicatorCSS- boolean: inject indicator CSS (default:true)defaultTimeout- number: default request timeout in ms (default:60000)inlineScriptNonce- string: nonce to add to inline scripts (default:'')inlineStyleNonce- string: nonce to add to inline styles (default:'')extensions- string: comma-separated list of extensions to load (default:'')sse- object: SSE/streaming configuration properties:reconnect- boolean: whether to reconnect on disconnect (default:false)reconnectMaxAttempts- number (default:10)reconnectDelay- number in ms (default:500)reconnectMaxDelay- number in ms (default:60000)reconnectJitter- number: jitter factor for reconnect delay (default:0.3)closeOnHide- boolean (default:false)
morphIgnore- array: attribute names to ignore when morphing (default:["data-htmx-powered"])noSwap- array: HTTP status codes that should not trigger a swap (default:[204, 304])implicitInheritance- boolean: inherit attributes automatically without:inherited(default:false)metaCharacter- string: custom character for attribute modifiers instead of:(default:undefined)version- string: the version of the current htmx library
Example
// enable debug logging
htmx.config.logAll = true;
// change default swap to outerHTML
htmx.config.defaultSwap = 'outerHTML';
// set custom attribute prefix
htmx.config.prefix = 'data-hx-';
// configure SSE streams
htmx.config.sse = {
reconnect: true,
reconnectMaxAttempts: 10,
reconnectDelay: 1000
};
Deprecated / Removed Methods
The following methods from htmx 2.x have been removed in htmx 4.x. Use the native browser equivalents:
htmx.addClass()- useelement.classList.add()htmx.removeClass()- useelement.classList.remove()htmx.toggleClass()- useelement.classList.toggle()htmx.closest()- useelement.closest()htmx.remove()- useelement.remove()htmx.logAll()- sethtmx.config.logAll = truehtmx.logNone()- sethtmx.config.logAll = falsehtmx.logger- use browser DevToolshtmx.off()- useremoveEventListener()htmx.removeExtension()- extensions are event-based, no removal neededhtmx.values()- access FormData directlyhtmx.createEventSource- removed (SSE is built-in)htmx.createWebSocket- removed (use extensions)
See the migration guide for more details on migrating from htmx 2.x to 4.x.