views – Behavior to use .insertAfter() on load + after each ajax call?

In Drupal ajaxComplete() is not required, as Drupal executes your Drupal.behaviors.*.attach() function each time an ajax call is complete. This function is passed the context variable, which on page load contains the entire contents of the document, and on AJAX calls contains the new part of the DOM being inserted into the page. This piece of the document can be parsed for the elements you are searching for. These two API points are combined with jQuery.once() to ensure that code is not executed on any piece of the DOM more than once.


(function ($, Drupal) {

   * Does something.
   * @param DOMelement
   *   Contains a the full document on page load, or new parts of the
   *   DOM being inserted into the page after ajax calls.
  function doSomething(context) {
    $(context).find(".some_dom_element").once("arbitrary-key").each(function () {
      // Do some stuff a single time on each instance of .some_dom_element that
      // appears on the page, both on page load and after any ajax loads.

  Drupal.behaviors.someArbitraryKey = {
    attach: function (context) {
}(jQuery, Drupal));

Note that if you create your own ajax calls, you will need to pass any new parts of the DOM to Drupal.attachBehaviors():

  url: '/path/to/ajax/callback',
  complete: function (data) {
    var newContent = $(data);
    // Pass the DOM element the jQuery object contains,
    // not the jQuery object: