diff --git a/core/misc/ajax.js b/core/misc/ajax.js
index fefe9f3031..bbaa0be44b 100644
--- a/core/misc/ajax.js
+++ b/core/misc/ajax.js
@@ -1027,22 +1027,52 @@
       // $(response.data) as new HTML rather than a CSS selector. Also, if
       // response.data contains top-level text nodes, they get lost with either
       // $(response.data) or $('<div></div>').replaceWith(response.data).
-      var $new_content_wrapped = $('<div></div>').html(response.data);
-      var $new_content = $new_content_wrapped.contents();
-
-      // For legacy reasons, the effects processing code assumes that
-      // $new_content consists of a single top-level element. Also, it has not
-      // been sufficiently tested whether attachBehaviors() can be successfully
-      // called with a context object that includes top-level text nodes.
-      // However, to give developers full control of the HTML appearing in the
-      // page, and to enable Ajax content to be inserted in places where <div>
-      // elements are not allowed (e.g., within <table>, <tr>, and <span>
-      // parents), we check if the new content satisfies the requirement
-      // of a single top-level element, and only use the container <div> created
-      // above when it doesn't. For more information, please see
-      // https://www.drupal.org/node/736066.
-      if ($new_content.length !== 1 || $new_content.get(0).nodeType !== 1) {
-        $new_content = $new_content_wrapped;
+      // attachBehaviors() can, for the same reason, not be called with a
+      // context object that includes top-level text nodes. Therefore text nodes
+      // will be wrapped with a <span> element. This also gives themers the
+      // possibility to style the response.
+
+      var $responseDataWrapped = $('<div></div>').html(response.data);
+      var $new_content = $('<div></div>');
+      var elementsReturnedCount = $responseDataWrapped.contents().length;
+
+      // If only one node element is returned skip wrap processing.
+      if (elementsReturnedCount === 1 && response.data === Node.ELEMENT_NODE) {
+        $new_content = response.data;
+      }
+      else {
+        var $intermediateWrapper = null;
+
+        $responseDataWrapped.contents().each(function (index, value) {
+          // Make sure all not-element nodes are wrapped.
+          if (value.nodeType !== Node.ELEMENT_NODE) {
+            if ($intermediateWrapper) {
+              $intermediateWrapper.append(value);
+            }
+            // Make an exception for comments that are not after a text node.
+            // This is especially helpful for when theme debugging is turned on.
+            else if (value.nodeType === Node.COMMENT_NODE) {
+              $new_content.append(value);
+            }
+            // Only create a wrapper if there is more than whitespace.
+            else if ($.trim(value.nodeValue).length) {
+              $intermediateWrapper = $('<span></span>');
+              $intermediateWrapper.append(value);
+            }
+          }
+          else {
+            $new_content.append($intermediateWrapper, value);
+            $intermediateWrapper = null;
+          }
+
+          // There are no other elements to process anymore, so add the
+          // intermediate wrapper to the content if present.
+          if (index === elementsReturnedCount - 1 && $intermediateWrapper) {
+            $new_content.append($intermediateWrapper);
+          }
+        });
+
+        $new_content = $new_content.contents();
       }
 
       // If removing content from the wrapper, detach behaviors first.
@@ -1053,7 +1083,10 @@
         case 'empty':
         case 'remove':
           settings = response.settings || ajax.settings || drupalSettings;
-          Drupal.detachBehaviors($wrapper.get(0), settings);
+          // Detach behaviors of all the to be removed element nodes.
+          $wrapper.children().each(function () {
+            Drupal.detachBehaviors(this, settings);
+          });
       }
 
       // Add the new content to the page.
@@ -1081,7 +1114,12 @@
       if ($new_content.parents('html').length > 0) {
         // Apply any settings from the returned JSON if available.
         settings = response.settings || ajax.settings || drupalSettings;
-        Drupal.attachBehaviors($new_content.get(0), settings);
+        // Attach behaviors to all element nodes.
+        $new_content.each(function () {
+          if (this.nodeType === Node.ELEMENT_NODE) {
+            Drupal.attachBehaviors(this, settings);
+          }
+        });
       }
     },
 
diff --git a/core/modules/system/tests/modules/ajax_test/ajax_test.libraries.yml b/core/modules/system/tests/modules/ajax_test/ajax_test.libraries.yml
index f1c73064bd..772a05f734 100644
--- a/core/modules/system/tests/modules/ajax_test/ajax_test.libraries.yml
+++ b/core/modules/system/tests/modules/ajax_test/ajax_test.libraries.yml
@@ -1,3 +1,8 @@
+ajax_insert:
+  js:
+    js/insert-ajax.js: {}
+  dependencies:
+    - core/drupal.ajax
 order:
  drupalSettings:
    ajax: test
diff --git a/core/modules/system/tests/modules/ajax_test/ajax_test.routing.yml b/core/modules/system/tests/modules/ajax_test/ajax_test.routing.yml
index e8d06c0a9f..89191a1c63 100644
--- a/core/modules/system/tests/modules/ajax_test/ajax_test.routing.yml
+++ b/core/modules/system/tests/modules/ajax_test/ajax_test.routing.yml
@@ -6,6 +6,14 @@ ajax_test.dialog_contents:
   requirements:
     _access: 'TRUE'
 
+ajax_test.ajax_render_types:
+  path: '/ajax-test/dialog-contents-types/{type}'
+  defaults:
+    _title: 'AJAX Dialog contents routing'
+    _controller: '\Drupal\ajax_test\Controller\AjaxTestController::renderTypes'
+  requirements:
+    _access: 'TRUE'
+
 ajax_test.dialog_form:
   path: '/ajax-test/dialog-form'
   defaults:
@@ -21,6 +29,13 @@ ajax_test.dialog:
   requirements:
     _access: 'TRUE'
 
+ajax_test.insert_links:
+  path: '/ajax-test/insert'
+  defaults:
+    _controller: '\Drupal\ajax_test\Controller\AjaxTestController::insertLinks'
+  requirements:
+    _access: 'TRUE'
+
 ajax_test.dialog_close:
   path: '/ajax-test/dialog-close'
   defaults:
diff --git a/core/modules/system/tests/modules/ajax_test/js/insert-ajax.js b/core/modules/system/tests/modules/ajax_test/js/insert-ajax.js
new file mode 100644
index 0000000000..38c11e60e6
--- /dev/null
+++ b/core/modules/system/tests/modules/ajax_test/js/insert-ajax.js
@@ -0,0 +1,27 @@
+/**
+ * @file
+ * Provides method to test ajax requests.
+ */
+
+(function ($, window, Drupal, drupalSettings) {
+  'use strict';
+
+  Drupal.behaviors.insertTest = {
+    attach: function (context, settings) {
+      $('.ajax-insert').once('ajax-insert').on('click', function (event) {
+        event.preventDefault();
+        var ajaxSettings = {
+          url: event.currentTarget.getAttribute('href'),
+          wrapper: 'ajax-target',
+          base: false,
+          element: false,
+          method: event.currentTarget.getAttribute('data-method')
+        };
+        var myAjaxObject = Drupal.ajax(ajaxSettings);
+        myAjaxObject.execute();
+      });
+
+      $(context).addClass('processed');
+    }
+  };
+})(jQuery, window, Drupal, drupalSettings);
diff --git a/core/modules/system/tests/modules/ajax_test/src/Controller/AjaxTestController.php b/core/modules/system/tests/modules/ajax_test/src/Controller/AjaxTestController.php
index 5ba65e8013..ca45a678b9 100644
--- a/core/modules/system/tests/modules/ajax_test/src/Controller/AjaxTestController.php
+++ b/core/modules/system/tests/modules/ajax_test/src/Controller/AjaxTestController.php
@@ -43,6 +43,60 @@ public static function dialogContents() {
   }
 
   /**
+   * Example content for testing whether response should be wrapped in div.
+   *
+   * @param string $type
+   *   Type of response.
+   *
+   * @return array
+   *   Renderable array of AJAX response contents.
+   */
+  public function renderTypes($type) {
+    $content = [
+      '#title' => '<em>AJAX Dialog & contents</em>',
+      'content' => [
+        '#type' => 'inline_template',
+        '#template' => $this->getRenderTypes()[$type],
+      ],
+    ];
+
+    return $content;
+  }
+
+  /**
+   * Returns a render array of links that directly Drupal.ajax().
+   */
+  public function insertLinks() {
+    $methods = [
+      'html',
+      'replaceWith',
+    ];
+
+    $build['links'] = [
+      'ajax_target' => [
+        '#markup' => '<div id="ajax-target">Target</div>',
+      ],
+      'links' => [
+        '#theme' => 'links',
+        '#attached' => ['library' => ['ajax_test/ajax_insert']],
+      ],
+    ];
+    foreach ($methods as $method) {
+      foreach (array_keys($this->getRenderTypes()) as $type) {
+        $build['links']['links']['#links']["$method-$type"] = [
+          'title' => "Link $method $type",
+          'url' => Url::fromRoute('ajax_test.ajax_render_types', ['type' => $type]),
+          'attributes' => [
+            'class' => ['ajax-insert'],
+            'data-method' => $method,
+          ],
+        ];
+      }
+    }
+    return $build;
+  }
+
+  /**
    * Returns a render array that will be rendered by AjaxRenderer.
    *
    * Verifies that the response incorporates JavaScript settings generated
@@ -222,4 +276,21 @@ public function dialogClose() {
     return $response;
   }
 
+  /**
+   * Render types.
+   *
+   * @return array
+   *   Render types.
+   */
+  protected function getRenderTypes() {
+    return [
+      'pre-wrapped' => '<div class="pre-wrapped">pre-wrapped</div>',
+      'pre-wrapped-leading-whitespace' => ' <div class="pre-wrapped-leading-whitespace">pre-wrapped-leading-whitespace</div>',
+      'not-wrapped' => 'not-wrapped',
+      'comment-not-wrapped' => '<!-- COMMENT --><div class="comment-not-wrapped">comment-not-wrapped</div>',
+      'mixed' => ' foo <!-- COMMENT -->  foo bar<div class="a class"><p>some string</p></div> additional not wrapped strings, <!-- ANOTHER COMMENT --> <p>final string</p>',
+    ];
+  }
+
 }
+
diff --git a/core/tests/Drupal/FunctionalJavascriptTests/Ajax/AjaxTest.php b/core/tests/Drupal/FunctionalJavascriptTests/Ajax/AjaxTest.php
index e05940537c..0e8a20dbba 100644
--- a/core/tests/Drupal/FunctionalJavascriptTests/Ajax/AjaxTest.php
+++ b/core/tests/Drupal/FunctionalJavascriptTests/Ajax/AjaxTest.php
@@ -16,6 +16,19 @@ class AjaxTest extends JavascriptTestBase {
    */
   public static $modules = ['ajax_test'];
 
+  /**
+   * Wrap HTML with an AJAX target div.
+   *
+   * @param string $html
+   *   The HTML to wrap.
+   *
+   * @return string
+   *   The HTML wrapped in the an AJAX target div.
+   */
+  protected function wrapAjaxTarget($html) {
+    return '<div id="ajax-target">' . $html . '</div>';
+  }
+
   public function testAjaxWithAdminRoute() {
     \Drupal::service('theme_installer')->install(['stable', 'seven']);
     $theme_config = \Drupal::configFactory()->getEditable('system.theme');
@@ -82,4 +95,70 @@ public function testDrupalSettingsCachingRegression() {
     $this->assertNotContains($fake_library, $libraries);
   }
 
+  /**
+   * Tests that various AJAX responses with DOM elements are correctly inserted.
+   *
+   * After inserting DOM elements, Drupal JavaScript behaviors should be
+   * reattached and all top-level elements of type Node.ELEMENT_NODE need to be
+   * part of the context.
+   */
+  public function testInsert() {
+    $assert = $this->assertSession();
+
+    $test_cases = [
+      // Test that no additional wrapper is added when inserting already wrapped
+      // response data and all top-level node elements (context) are processed
+      // correctly.
+      [
+        'render_type' => 'pre-wrapped',
+        'expected' => '<div class="pre-wrapped processed">pre-wrapped</div>',
+      ],
+      // Test that no additional empty leading div is added when the return
+      // value had a leading space and all top-level node elements (context) are
+      // processed correctly.
+      [
+        'render_type' => 'pre-wrapped-leading-whitespace',
+        'expected' => '<div class="pre-wrapped-leading-whitespace processed">pre-wrapped-leading-whitespace</div>',
+      ],
+      // Test that not wrapped response data (text node) is inserted wrapped and
+      // all top-level node elements (context) are processed correctly.
+      [
+        'render_type' => 'not-wrapped',
+        'expected' => '<span class="processed">not-wrapped</span>',
+      ],
+      // Test that top-level comments (which are not lead by text nodes) are
+      // inserted without wrapper.
+      [
+        'render_type' => 'comment-not-wrapped',
+        'expected' => '<!-- COMMENT --><div class="comment-not-wrapped processed">comment-not-wrapped</div>',
+      ],
+      // Test that wrappend and not-wrapped response data is inserted correctly
+      // and all top-level node elements (context) are processed correctly.
+      [
+        'method' => 'html',
+        'render_type' => 'mixed',
+        'expected' => '<span class="processed"> foo <!-- COMMENT -->  foo bar</span><div class="a class processed"><p>some string</p></div><span class="processed"> additional not wrapped strings, <!-- ANOTHER COMMENT --> </span><p class="processed">final string</p>',
+      ],
+
+    ];
+
+    foreach (['html', 'replaceWith'] as $method) {
+      foreach ($test_cases as $test_case) {
+        $this->drupalGet('ajax-test/insert');
+        $this->clickLink("Link $method {$test_case['render_type']}");
+        $assert->assertWaitOnAjaxRequest();
+        switch ($method) {
+          case 'html':
+            $assert->responseContains($this->wrapAjaxTarget($test_case['expected']));
+            break;
+
+          case 'replaceWith':
+            $assert->responseContains($test_case['expected']);
+            $assert->responseNotContains($this->wrapAjaxTarget($test_case['expected']));
+            break;
+        }
+      }
+    }
+  }
+
 }
