Core htmx JavaScript API Methods: A Complete Developer Reference

The htmx JavaScript API exposes a stable global htmx object with over 20 methods for event handling, DOM manipulation, AJAX requests, and extension management, all implemented as thin wrappers in src/htmx.js that forward to internal helpers.

The bigskysoftware/htmx library provides a compact yet powerful public API that enables programmatic control over hypermedia interactions. Understanding these htmx JavaScript API methods allows developers to manually trigger swaps, register event listeners, and extend the library's core functionality beyond declarative HTML attributes.

Event Handling Methods

The API provides four core methods for managing the htmx event lifecycle. Each method is exposed as a lightweight wrapper that forwards to internal implementations defined later in src/htmx.js.

htmx.onLoad(callback)

Registers a listener for the htmx:load event that fires after new content is processed and settled. In the source code, this maps to the onLoadHelper function on lines 82-88 of src/htmx.js.

htmx.onLoad(function (elt) {
  console.log("New content loaded:", elt);
});

htmx.on(target, event, listener, options?)

Adds an event listener to a specific element or the document body if the target is omitted. This method wraps addEventListenerImpl (lines 317-324) and supports optional event listener options such as once or passive.

htmx.on(document.body, "htmx:beforeSwap", function (evt) {
  console.log("About to swap:", evt.detail.target);
});

htmx.off(target, event, listener)

Removes a previously attached event listener, mapping directly to removeEventListenerImpl on lines 336-342. Use this for cleanup when dynamically removing elements that have registered handlers.

htmx.trigger(elt, name, detail?)

Dispatches a custom event on an element with an optional detail payload. This wraps triggerEvent (lines 1498-1504) and is useful for programmatically firing htmx events or custom application events.

htmx.trigger(document.querySelector("#myBtn"), "myCustomEvent", {info: 42});

DOM Processing and Querying

These methods allow manual activation of htmx attributes and efficient DOM traversal without external dependencies.

htmx.process(elt)

Walks a DOM subtree and activates any htmx attributes found within the element. This is essential when injecting HTML dynamically via JavaScript rather than through htmx requests. The method wraps processNode, which is assigned to the public API on line 303 of src/htmx.js.

let fragment = document.createRange().createContextualFragment("<div hx-get='/foo'></div>");
htmx.process(fragment);

htmx.find(selector) and htmx.findAll(selector)

htmx.find returns the first element matching a CSS selector within the supplied root (or document), while htmx.findAll returns a NodeList of all matches. These wrap the internal find (lines 15-21) and findAll (lines 23-30) functions respectively.

let btn = htmx.find("#myBtn");
let allRows = htmx.findAll("table tr");

htmx.closest(elt, selector)

Finds the nearest ancestor (including the element itself) that matches the provided selector. This maps to the closest helper on lines 84-90.

AJAX and Network Requests

htmx.ajax(verb, path, elt)

Performs an XHR request using the supplied HTTP verb and URL, with the elt parameter providing request context for headers and targeting. This wraps ajaxHelper, assigned on line 306, and respects all standard htmx configuration options.

htmx.ajax("POST", "/api/save", document.querySelector("#form"));

htmx.values(elt, type?)

Returns an object containing resolved input values for an element, useful for manually constructing fetch requests or debugging form data. This maps to the values helper on lines 36-40.

let payload = htmx.values(document.querySelector("#form"));
fetch("/api/save", {method: "POST", body: JSON.stringify(payload)});

DOM Manipulation Utilities

htmx exposes several methods for class manipulation and element removal that mirror common jQuery patterns but leverage modern browser APIs.

Class Management Methods

  • htmx.addClass(elt, clazz, delay?) – Adds a CSS class immediately or after a specified delay in milliseconds. Wraps addClassToElement (lines 108-121).
  • htmx.removeClass(elt, clazz, delay?) – Removes a CSS class immediately or after a delay. Wraps removeClassFromElement (lines 132-151).
  • htmx.toggleClass(elt, clazz) – Toggles a class on the element. Wraps toggleClassOnElement (lines 161-165).
  • htmx.takeClass(elt, clazz) – Ensures only the given element among its siblings has the specified class, effectively creating a mutually exclusive selection pattern. Wraps takeClassForElement (lines 174-180).
htmx.addClass(btn, "highlight", 200);   // add after 200ms
htmx.toggleClass(btn, "active");
htmx.takeClass(tab, "active-tab");

htmx.remove(elt, delay?)

Removes an element from the DOM, optionally after a timeout. This wraps removeElement on lines 55-65 and is used internally for the hx-swap="delete" functionality.

htmx.swap(target, fragment, settleInfo)

Performs the low-level content swap according to htmx's swap algorithm. This method wraps swap (lines 51-53) and accepts settlement information to handle settling transitions and script evaluation.

Extension Management

htmx.defineExtension(name, extension)

Registers a new htmx extension (such as ws for WebSockets or sse for Server-Sent Events) by mapping to defineExtension on lines 54-56. Extensions must implement specific lifecycle hooks to integrate with htmx's request pipeline.

htmx.removeExtension(name)

Unregisters a previously defined extension by name, wrapping removeExtension on lines 57-59.

Debugging and Utility Functions

htmx.logAll() and htmx.logNone()

Toggle a global logger that prints all htmx events to the browser console. These wrap logAll (lines 94-99) and logNone (lines 101-104), providing invaluable debugging visibility into the htmx event lifecycle.

htmx.logAll();   // start logging all events
// ... application code ...
htmx.logNone();  // silence the logger

htmx.parseInterval(str)

Parses timing strings such as "200ms", "2s", or "5m" into millisecond integers. This utility wraps parseInterval on lines 73-89 and is useful for custom timing calculations in extensions or event handlers.

htmx._(str)

Evaluates a string in a safe sandbox environment, used internally for hx-vars and similar attribute evaluations. This maps to internalEval on lines 268-272.

htmx.version

Exposes the current library version as a string (e.g., "2.0.10"), defined in the htmx object instantiation on line 299 of src/htmx.js.

Practical Implementation Examples

The following snippets demonstrate common patterns using the htmx JavaScript API methods in production applications.

// Manually process dynamically injected content
let container = document.getElementById("dynamic-container");
container.innerHTML = "<button hx-get='/data' hx-target='#result'>Load</button>";
htmx.process(container);

// Listen for swap events with cleanup
function handleBeforeSwap(evt) {
  if (!evt.detail.xhr.responseText.includes("valid")) {
    evt.preventDefault();
  }
}
htmx.on(document, "htmx:beforeSwap", handleBeforeSwap);

// Utility: Remove after animation
htmx.addClass(modal, "fade-out", 0);
htmx.remove(modal, 300);  // remove after 300ms

// Debug mode for development
if (location.hostname === "localhost") {
  htmx.logAll();
}

Summary

  • The htmx JavaScript API lives on the global htmx object instantiated at the top of src/htmx.js (lines 4-30).
  • Public methods are thin wrappers assigned on lines 302-321 that forward to internal implementations, ensuring API stability while allowing internal refactoring.
  • Core categories include event handling (on, off, trigger, onLoad), DOM processing (process, find, closest), AJAX (ajax, values), and utilities (parseInterval, logAll).
  • The extension API (defineExtension, removeExtension) enables third-party plugins that hook into the request lifecycle.
  • Version metadata is accessible via htmx.version, currently returning "2.0.10" as defined in the source.

Frequently Asked Questions

How do I manually trigger an htmx request using the JavaScript API?

Use htmx.ajax(verb, path, element) to initiate requests programmatically. The element parameter provides context for target resolution and header configuration, while the method wraps the internal ajaxHelper function assigned on line 306 of src/htmx.js.

What is the difference between htmx.process and htmx.ajax?

htmx.process scans existing DOM elements for htmx attributes and initializes them without making network requests, while htmx.ajax performs an actual HTTP request using the specified verb and URL. Use process when injecting HTML via JavaScript; use ajax when you need to fetch data from the server manually.

Can I use htmx.find instead of document.querySelector?

Yes. htmx.find serves as a lightweight wrapper around the browser's query selector that respects htmx's internal root context, though it functions similarly to document.querySelector. The method wraps the internal find helper on lines 15-21 and is guaranteed to work consistently across htmx's supported browser matrix.

How do I unregister an event listener properly?

Call htmx.off(target, event, listener) passing the same function reference used during registration. Because htmx wraps native event listeners through addEventListenerImpl (lines 317-324) and removeEventListenerImpl (lines 336-342), using the library's methods ensures proper cleanup and prevents memory leaks in long-running single-page applications.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →