diff --git a/core/misc/ajax.es6.js b/core/misc/ajax.es6.js
index c3633b4636..7796dfd49a 100644
--- a/core/misc/ajax.es6.js
+++ b/core/misc/ajax.es6.js
@@ -1025,39 +1025,35 @@
      *   A optional jQuery selector string.
      * @param {object} [response.settings]
      *   An optional array of settings that will be used.
-     * @param {number} [status]
-     *   The XMLHttpRequest status.
      */
-    insert(ajax, response, status) {
+    insert(ajax, response) {
       // Get information from the response. If it is not there, default to
       // our presets.
       const $wrapper = response.selector ? $(response.selector) : $(ajax.wrapper);
       const method = response.method || ajax.method;
       const effect = ajax.getEffect(response);
-      let settings;
-
-      // We don't know what response.data contains: it might be a string of text
-      // without HTML, so don't rely on jQuery correctly interpreting
-      // $(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).
-      const $newContentWrapped = $('<div></div>').html(response.data);
-      let $newContent = $newContentWrapped.contents();
-
-      // For legacy reasons, the effects processing code assumes that
-      // $newContent 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 ($newContent.length !== 1 || $newContent.get(0).nodeType !== 1) {
-        $newContent = $newContentWrapped;
-      }
+
+      // Apply any settings from the returned JSON if available.
+      const settings = response.settings || ajax.settings || drupalSettings;
+
+      // Store SVG elements
+      const svgStorage = {};
+
+      // Parse response.data into an element collection.
+      const $newContent = $($.parseHTML(response.data, true).map((element) => {
+        // If the response contains an SVG, replace it with a placeholder.
+        if (element.nodeName && element.nodeName === 'svg') {
+          // Create an ID to reference later.
+          const hash = `svg-${Math.random().toString(36).substring(7)}`;
+          svgStorage[hash] = element.outerHTML;
+
+          // Create a plceholder DIV that will be replaced with the SVG.
+          const svgPlaceHolder = document.createElement('div');
+          svgPlaceHolder.id = hash;
+          return svgPlaceHolder;
+        }
+        return element;
+      }));
 
       // If removing content from the wrapper, detach behaviors first.
       switch (method) {
@@ -1066,13 +1062,23 @@
         case 'replaceAll':
         case 'empty':
         case 'remove':
-          settings = response.settings || ajax.settings || drupalSettings;
           Drupal.detachBehaviors($wrapper.get(0), settings);
+          break;
+        default:
+          break;
       }
 
       // Add the new content to the page.
       $wrapper[method]($newContent);
 
+      // If there is any SVG data, start replacing them.
+      if (Object.keys(svgStorage).length) {
+        Object.keys(svgStorage).forEach((key) => {
+          // Replace each placeholder DIV with the saved SVG data.
+          $(`#${key}`).replaceWith(svgStorage[key]);
+        });
+      }
+
       // Immediately hide the new content if we're using any effects.
       if (effect.showEffect !== 'show') {
         $newContent.hide();
@@ -1080,10 +1086,11 @@
 
       // Determine which effect to use and what content will receive the
       // effect, then show the new content.
-      if ($newContent.find('.ajax-new-content').length > 0) {
-        $newContent.find('.ajax-new-content').hide();
+      const $ajaxNewContent = $newContent.find('.ajax-new-content');
+      if ($ajaxNewContent.length) {
+        $ajaxNewContent.hide();
         $newContent.show();
-        $newContent.find('.ajax-new-content')[effect.showEffect](effect.showSpeed);
+        $ajaxNewContent[effect.showEffect](effect.showSpeed);
       }
       else if (effect.showEffect !== 'show') {
         $newContent[effect.showEffect](effect.showSpeed);
@@ -1092,10 +1099,13 @@
       // Attach all JavaScript behaviors to the new content, if it was
       // successfully added to the page, this if statement allows
       // `#ajax['wrapper']` to be optional.
-      if ($newContent.parents('html').length > 0) {
-        // Apply any settings from the returned JSON if available.
-        settings = response.settings || ajax.settings || drupalSettings;
-        Drupal.attachBehaviors($newContent.get(0), settings);
+      if ($newContent.parents('html').length) {
+        // Attach behaviors to all element nodes.
+        $newContent.each((index, element) => {
+          if (element.nodeType === Node.ELEMENT_NODE) {
+            Drupal.attachBehaviors(element, settings);
+          }
+        });
       }
     },
 
diff --git a/core/misc/ajax.js b/core/misc/ajax.js
index 58759ac7a0..7977ee5d31 100644
--- a/core/misc/ajax.js
+++ b/core/misc/ajax.js
@@ -480,18 +480,26 @@ function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr
 
   Drupal.AjaxCommands = function () {};
   Drupal.AjaxCommands.prototype = {
-    insert: function insert(ajax, response, status) {
+    insert: function insert(ajax, response) {
       var $wrapper = response.selector ? $(response.selector) : $(ajax.wrapper);
       var method = response.method || ajax.method;
       var effect = ajax.getEffect(response);
-      var settings = void 0;
 
-      var $newContentWrapped = $('<div></div>').html(response.data);
-      var $newContent = $newContentWrapped.contents();
+      var settings = response.settings || ajax.settings || drupalSettings;
 
-      if ($newContent.length !== 1 || $newContent.get(0).nodeType !== 1) {
-        $newContent = $newContentWrapped;
-      }
+      var svgStorage = {};
+
+      var $newContent = $($.parseHTML(response.data, true).map(function (element) {
+        if (element.nodeName && element.nodeName === 'svg') {
+          var hash = 'svg-' + Math.random().toString(36).substring(7);
+          svgStorage[hash] = element.outerHTML;
+
+          var svgPlaceHolder = document.createElement('div');
+          svgPlaceHolder.id = hash;
+          return svgPlaceHolder;
+        }
+        return element;
+      }));
 
       switch (method) {
         case 'html':
@@ -499,27 +507,39 @@ function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr
         case 'replaceAll':
         case 'empty':
         case 'remove':
-          settings = response.settings || ajax.settings || drupalSettings;
           Drupal.detachBehaviors($wrapper.get(0), settings);
+          break;
+        default:
+          break;
       }
 
       $wrapper[method]($newContent);
 
+      if (Object.keys(svgStorage).length) {
+        Object.keys(svgStorage).forEach(function (key) {
+          $('#' + key).replaceWith(svgStorage[key]);
+        });
+      }
+
       if (effect.showEffect !== 'show') {
         $newContent.hide();
       }
 
-      if ($newContent.find('.ajax-new-content').length > 0) {
-        $newContent.find('.ajax-new-content').hide();
+      var $ajaxNewContent = $newContent.find('.ajax-new-content');
+      if ($ajaxNewContent.length) {
+        $ajaxNewContent.hide();
         $newContent.show();
-        $newContent.find('.ajax-new-content')[effect.showEffect](effect.showSpeed);
+        $ajaxNewContent[effect.showEffect](effect.showSpeed);
       } else if (effect.showEffect !== 'show') {
         $newContent[effect.showEffect](effect.showSpeed);
       }
 
-      if ($newContent.parents('html').length > 0) {
-        settings = response.settings || ajax.settings || drupalSettings;
-        Drupal.attachBehaviors($newContent.get(0), settings);
+      if ($newContent.parents('html').length) {
+        $newContent.each(function (index, element) {
+          if (element.nodeType === Node.ELEMENT_NODE) {
+            Drupal.attachBehaviors(element, settings);
+          }
+        });
       }
     },
     remove: function remove(ajax, response, status) {
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..875b7caa96 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,20 @@ ajax_test.dialog:
   requirements:
     _access: 'TRUE'
 
+ajax_test.insert_links_block_wrapper:
+  path: '/ajax-test/insert-block-wrapper'
+  defaults:
+    _controller: '\Drupal\ajax_test\Controller\AjaxTestController::insertLinksBlockWrapper'
+  requirements:
+    _access: 'TRUE'
+
+ajax_test.insert_links_inline_wrapper:
+  path: '/ajax-test/insert-inline-wrapper'
+  defaults:
+    _controller: '\Drupal\ajax_test\Controller\AjaxTestController::insertLinksInlineWrapper'
+  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.es6.js b/core/modules/system/tests/modules/ajax_test/js/insert-ajax.es6.js
new file mode 100644
index 0000000000..e7fb3f212b
--- /dev/null
+++ b/core/modules/system/tests/modules/ajax_test/js/insert-ajax.es6.js
@@ -0,0 +1,39 @@
+/**
+ * @file
+ * Drupal behavior to attach click event handlers to ajax-insert and
+ * ajax-insert-inline links for testing ajax requests.
+ */
+
+(function ($, window, Drupal) {
+  Drupal.behaviors.insertTest = {
+    attach(context) {
+      $('.ajax-insert').once('ajax-insert').on('click', (event) => {
+        event.preventDefault();
+        const ajaxSettings = {
+          url: event.currentTarget.getAttribute('href'),
+          wrapper: 'ajax-target',
+          base: false,
+          element: false,
+          method: event.currentTarget.getAttribute('data-method'),
+        };
+        const myAjaxObject = Drupal.ajax(ajaxSettings);
+        myAjaxObject.execute();
+      });
+
+      $('.ajax-insert-inline').once('ajax-insert').on('click', (event) => {
+        event.preventDefault();
+        const ajaxSettings = {
+          url: event.currentTarget.getAttribute('href'),
+          wrapper: 'ajax-target-inline',
+          base: false,
+          element: false,
+          method: event.currentTarget.getAttribute('data-method'),
+        };
+        const myAjaxObject = Drupal.ajax(ajaxSettings);
+        myAjaxObject.execute();
+      });
+
+      $(context).addClass('processed');
+    },
+  };
+}(jQuery, window, Drupal));
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..c261bca80a
--- /dev/null
+++ b/core/modules/system/tests/modules/ajax_test/js/insert-ajax.js
@@ -0,0 +1,40 @@
+/**
+* DO NOT EDIT THIS FILE.
+* See the following change record for more information,
+* https://www.drupal.org/node/2815083
+* @preserve
+**/
+
+(function ($, window, Drupal) {
+  Drupal.behaviors.insertTest = {
+    attach: function attach(context) {
+      $('.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();
+      });
+
+      $('.ajax-insert-inline').once('ajax-insert').on('click', function (event) {
+        event.preventDefault();
+        var ajaxSettings = {
+          url: event.currentTarget.getAttribute('href'),
+          wrapper: 'ajax-target-inline',
+          base: false,
+          element: false,
+          method: event.currentTarget.getAttribute('data-method')
+        };
+        var myAjaxObject = Drupal.ajax(ajaxSettings);
+        myAjaxObject.execute();
+      });
+
+      $(context).addClass('processed');
+    }
+  };
+})(jQuery, window, Drupal);
\ No newline at end of file
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..9b6a9e2cef 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
@@ -42,6 +42,101 @@ public static function dialogContents() {
     return $content;
   }
 
+  /**
+   * 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().
+   *
+   * @return array
+   *   Renderable array of AJAX response contents.
+   */
+  public function insertLinksBlockWrapper() {
+    $methods = [
+      'html',
+      'replaceWith',
+    ];
+
+    $build['links'] = [
+      'ajax_target' => [
+        '#markup' => '<div class="ajax-target-wrapper"><div id="ajax-target">Target</div></div>',
+      ],
+      'links' => [
+        '#theme' => 'links',
+        '#attached' => ['library' => ['ajax_test/ajax_insert']],
+      ],
+    ];
+    foreach ($methods as $method) {
+      foreach (array_keys($this->getRenderTypes()) as $type) {
+        $class = 'ajax-insert';
+        $build['links']['links']['#links']["$method-$type"] = [
+          'title' => "Link $method $type",
+          'url' => Url::fromRoute('ajax_test.ajax_render_types', ['type' => $type]),
+          'attributes' => [
+            'class' => [$class],
+            'data-method' => $method,
+          ],
+        ];
+      }
+    }
+    return $build;
+  }
+
+  /**
+   * Returns a render array of links that directly Drupal.ajax().
+   *
+   * @return array
+   *   Renderable array of AJAX response contents.
+   */
+  public function insertLinksInlineWrapper() {
+    $methods = [
+      'html',
+      'replaceWith',
+    ];
+
+    $build['links'] = [
+      'ajax_target' => [
+        '#markup' => '<div class="ajax-target-wrapper"><span id="ajax-target-inline">Target inline</span></div>',
+      ],
+      'links' => [
+        '#theme' => 'links',
+        '#attached' => ['library' => ['ajax_test/ajax_insert']],
+      ],
+    ];
+    foreach ($methods as $method) {
+      foreach (array_keys($this->getRenderTypes()) as $type) {
+        $class = 'ajax-insert-inline';
+        $build['links']['links']['#links']["$method-$type"] = [
+          'title' => "Link $method $type",
+          'url' => Url::fromRoute('ajax_test.ajax_render_types', ['type' => $type]),
+          'attributes' => [
+            'class' => [$class],
+            'data-method' => $method,
+          ],
+        ];
+      }
+    }
+    return $build;
+  }
+
   /**
    * Returns a render array that will be rendered by AjaxRenderer.
    *
@@ -222,4 +317,28 @@ public function dialogClose() {
     return $response;
   }
 
+  /**
+   * Render types.
+   *
+   * @return array
+   *   Render types.
+   */
+  protected function getRenderTypes() {
+    return [
+      'pre-wrapped-div' => '<div class="pre-wrapped">pre-wrapped<script> var test;</script></div>',
+      'pre-wrapped-span' => '<span class="pre-wrapped">pre-wrapped<script> var test;</script></span>',
+      'pre-wrapped-whitespace' => ' <div class="pre-wrapped-whitespace">pre-wrapped-whitespace</div>' . "\r\n",
+      'not-wrapped' => 'not-wrapped',
+      'comment-string-not-wrapped' => '<!-- COMMENT -->comment-string-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>',
+      'top-level-only' => '<div>element #1</div><div>element #2</div>',
+      'top-level-only-pre-whitespace' => ' <div>element #1</div><div>element #2</div> ',
+      'top-level-only-middle-whitespace-span' => '<span>element #1</span> <span>element #2</span>',
+      'top-level-only-middle-whitespace-div' => '<div>element #1</div> <div>element #2</div>',
+      'svg' => '<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect x="0" y="0" height="10" width="10" fill="green"/></svg>',
+      'empty' => '',
+    ];
+  }
+
 }
diff --git a/core/tests/Drupal/FunctionalJavascriptTests/Ajax/AjaxFormPageCacheTest.php b/core/tests/Drupal/FunctionalJavascriptTests/Ajax/AjaxFormPageCacheTest.php
index 3d174b04df..b8ede8f7aa 100644
--- a/core/tests/Drupal/FunctionalJavascriptTests/Ajax/AjaxFormPageCacheTest.php
+++ b/core/tests/Drupal/FunctionalJavascriptTests/Ajax/AjaxFormPageCacheTest.php
@@ -55,8 +55,8 @@ public function testSimpleAJAXFormValue() {
 
     // Wait for the DOM to update. The HtmlCommand will update
     // #ajax_selected_color to reflect the color change.
-    $green_div = $this->assertSession()->waitForElement('css', "#ajax_selected_color div:contains('green')");
-    $this->assertNotNull($green_div, 'DOM update: The selected color DIV is green.');
+    $green_span = $this->assertSession()->waitForElement('css', "#ajax_selected_color:contains('green')");
+    $this->assertNotNull($green_span, 'DOM update: The selected color SPAN is green.');
 
     // Confirm the operation of the UpdateBuildIdCommand.
     $build_id_first_ajax = $this->getFormBuildId();
@@ -67,8 +67,8 @@ public function testSimpleAJAXFormValue() {
     $session->getPage()->selectFieldOption('select', 'red');
 
     // Wait for the DOM to update.
-    $red_div = $this->assertSession()->waitForElement('css', "#ajax_selected_color div:contains('red')");
-    $this->assertNotNull($red_div, 'DOM update: The selected color DIV is red.');
+    $red_span = $this->assertSession()->waitForElement('css', "#ajax_selected_color:contains('red')");
+    $this->assertNotNull($red_span, 'DOM update: The selected color SPAN is red.');
 
     // Confirm the operation of the UpdateBuildIdCommand.
     $build_id_second_ajax = $this->getFormBuildId();
@@ -86,8 +86,8 @@ public function testSimpleAJAXFormValue() {
     $session->getPage()->selectFieldOption('select', 'green');
 
     // Wait for the DOM to update.
-    $green_div2 = $this->assertSession()->waitForElement('css', "#ajax_selected_color div:contains('green')");
-    $this->assertNotNull($green_div2, 'DOM update: After reload - the selected color DIV is green.');
+    $green_span2 = $this->assertSession()->waitForElement('css', "#ajax_selected_color:contains('green')");
+    $this->assertNotNull($green_span2, 'DOM update: After reload - the selected color SPAN is green.');
 
     $build_id_from_cache_first_ajax = $this->getFormBuildId();
     $this->assertNotEquals($build_id_from_cache_initial, $build_id_from_cache_first_ajax, 'Build id is changed in the simpletest-DOM on first AJAX submission');
@@ -98,8 +98,8 @@ public function testSimpleAJAXFormValue() {
     $session->getPage()->selectFieldOption('select', 'red');
 
     // Wait for the DOM to update.
-    $red_div2 = $this->assertSession()->waitForElement('css', "#ajax_selected_color div:contains('red')");
-    $this->assertNotNull($red_div2, 'DOM update: After reload - the selected color DIV is red.');
+    $red_span2 = $this->assertSession()->waitForElement('css', "#ajax_selected_color:contains('red')");
+    $this->assertNotNull($red_span2, 'DOM update: After reload - the selected color SPAN is red.');
 
     $build_id_from_cache_second_ajax = $this->getFormBuildId();
     $this->assertNotEquals($build_id_from_cache_first_ajax, $build_id_from_cache_second_ajax, 'Build id changes on subsequent AJAX submissions');
diff --git a/core/tests/Drupal/FunctionalJavascriptTests/Ajax/AjaxTest.php b/core/tests/Drupal/FunctionalJavascriptTests/Ajax/AjaxTest.php
index e05940537c..82d63d4099 100644
--- a/core/tests/Drupal/FunctionalJavascriptTests/Ajax/AjaxTest.php
+++ b/core/tests/Drupal/FunctionalJavascriptTests/Ajax/AjaxTest.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\FunctionalJavascriptTests\Ajax;
 
+use Drupal\FunctionalJavascriptTests\DrupalSelenium2Driver;
 use Drupal\FunctionalJavascriptTests\JavascriptTestBase;
 
 /**
@@ -11,6 +12,8 @@
  */
 class AjaxTest extends JavascriptTestBase {
 
+  protected $minkDefaultDriverClass = DrupalSelenium2Driver::class;
+
   /**
    * {@inheritdoc}
    */
@@ -82,4 +85,141 @@ 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.
+   *
+   * @dataProvider providerTestInsert
+   */
+  public function testInsertBlock($render_type, $expected) {
+    $this->drupalGet('ajax-test/insert-block-wrapper');
+    $this->clickLink("Link html $render_type");
+    $this->assertWaitPageContains('<div class="ajax-target-wrapper"><div id="ajax-target">' . $expected . '</div></div>');
+
+    $this->drupalGet('ajax-test/insert-block-wrapper');
+    $this->clickLink("Link replaceWith $render_type");
+    $this->assertWaitPageContains('<div class="ajax-target-wrapper">' . $expected . '</div>');
+  }
+
+  /**
+   * 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.
+   *
+   * @dataProvider providerTestInsert
+   */
+  public function testInsertInline($render_type, $expected) {
+    $this->drupalGet('ajax-test/insert-inline-wrapper');
+    $this->clickLink("Link html $render_type");
+    $this->assertWaitPageContains('<div class="ajax-target-wrapper"><span id="ajax-target-inline">' . $expected . '</span></div>');
+
+    $this->drupalGet('ajax-test/insert-inline-wrapper');
+    $this->clickLink("Link replaceWith $render_type");
+    $this->assertWaitPageContains('<div class="ajax-target-wrapper">' . $expected . '</div>');
+  }
+
+  /**
+   * Provides test result data.
+   */
+  public function providerTestInsert() {
+    $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.
+    $test_cases['pre_wrapped_div'] = [
+      'pre-wrapped-div',
+      '<div class="pre-wrapped processed">pre-wrapped<script> var test;</script></div>',
+    ];
+    $test_cases['pre_wrapped_span'] = [
+      'pre-wrapped-span',
+      '<span class="pre-wrapped processed">pre-wrapped<script> var test;</script></span>',
+    ];
+    // 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.
+    $test_cases['pre_wrapped_whitespace'] = [
+      'pre-wrapped-whitespace',
+      " <div class=\"pre-wrapped-whitespace processed\">pre-wrapped-whitespace</div>\n",
+    ];
+    // Test that not wrapped response data (text node) is inserted wrapped and
+    // all top-level node elements (context) are processed correctly.
+    $test_cases['not_wrapped'] = [
+      'not-wrapped',
+      'not-wrapped',
+    ];
+    // Test that not wrapped response data (text node and comment node) is
+    // inserted wrapped and all top-level node elements
+    // (context) are processed correctly.
+    $test_cases['comment_string_not_wrapped'] = [
+      'comment-string-not-wrapped',
+      '<!-- COMMENT -->comment-string-not-wrapped',
+    ];
+    // Test that top-level comments (which are not lead by text nodes) are
+    // inserted without wrapper.
+    $test_cases['comment_not_wrapped'] = [
+      'comment-not-wrapped',
+      '<!-- COMMENT --><div class="comment-not-wrapped processed">comment-not-wrapped</div>',
+    ];
+    // Test that mixed inline & block level elements and comments response data
+    // is inserted correctly.
+    $test_cases['mixed'] = [
+      'mixed',
+      ' foo <!-- COMMENT -->  foo bar<div class="a class processed"><p>some string</p></div> additional not wrapped strings, <!-- ANOTHER COMMENT --> <p class="processed">final string</p>',
+    ];
+    // Test that when the response has only top-level node elements, they
+    // are processed properly without extra wrapping.
+    $test_cases['top_level_only'] = [
+      'top-level-only',
+      '<div class="processed">element #1</div><div class="processed">element #2</div>',
+    ];
+    // Test that whitespaces at start or end don't wrap the response when
+    // there are multiple top-level nodes.
+    $test_cases['top_level_only_pre_whitespace'] = [
+      'top-level-only-pre-whitespace',
+      ' <div class="processed">element #1</div><div class="processed">element #2</div> ',
+    ];
+    // Test when there are whitespaces between top-level divs.
+    $test_cases['top_level_only_middle_whitespace-div'] = [
+      'top-level-only-middle-whitespace-div',
+      '<div class="processed">element #1</div> <div class="processed">element #2</div>',
+    ];
+    // Test when there are whitespaces between top-level spans.
+    $test_cases['top_level_only_middle_whitespace-span'] = [
+      'top-level-only-middle-whitespace-span',
+      '<span class="processed">element #1</span> <span class="processed">element #2</span>',
+    ];
+    // Test svg.
+    $test_cases['svg'] = [
+      'svg',
+      '<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect x="0" y="0" height="10" width="10" fill="green"/></svg>',
+    ];
+    // Test that empty response data.
+    $test_cases['empty'] = [
+      'empty',
+      '',
+    ];
+
+    return $test_cases;
+  }
+
+  /**
+   * Asserts that page contains a text after waiting.
+   *
+   * @param string $text
+   *   A needle text.
+   */
+  protected function assertWaitPageContains($text) {
+    $page = $this->getSession()->getPage();
+    $page->waitFor(10, function () use ($page, $text) {
+      return stripos($page->getContent(), $text) !== FALSE;
+    });
+    $this->assertContains($text, $page->getContent());
+  }
+
 }
