</> htmx
🚧 htmx 4.0 is under construction. Read changes →

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

or

or

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

or

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

or

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

or

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
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
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
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
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
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
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
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
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
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
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:

See the migration guide for more details on migrating from htmx 2.x to 4.x.