AfterCommand

Last updated on
22 January 2026

Ajax API

Inserts markup after a target element (jQuery after() semantics).

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\AfterCommand;

public function ajaxHandler(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $afterCommand = new AfterCommand(
    '#item', '<div class="note">Added after</div>'
  );
  $response->addCommand($afterCommand);
  return $response;
}

HTMX

Use hx-target for the reference element and hx-swap="afterend" to insert after it.

use Drupal\Core\Htmx\Htmx;

(new Htmx())
  ->post($formUrl)
  ->select('#after-fragment')    // element to insert
  ->target('#item')              // target element
  ->swap('afterend')             // insert after target
  ->applyTo($form['trigger']);

Documentation hx-swap

Help improve this page

Page status: No known problems

You can: