diff --git a/core/modules/simpletest/src/WebTestBase.php b/core/modules/simpletest/src/WebTestBase.php
index 2ac0d4b..11c2607 100644
--- a/core/modules/simpletest/src/WebTestBase.php
+++ b/core/modules/simpletest/src/WebTestBase.php
@@ -1922,9 +1922,13 @@ protected function drupalProcessAjaxResponse($content, array $ajax_response, arr
 
         case 'insert':
           $wrapperNode = NULL;
+          // When a command specifies a specific selector, use it.
+          if (!empty($command['selector']) && strpos($command['selector'], '#') === 0) {
+            $wrapperNode = $xpath->query('//*[@id="' . substr($command['selector'], 1) . '"]')->item(0);
+          }
           // When a command doesn't specify a selector, use the
           // #ajax['wrapper'] which is always an HTML ID.
-          if (!isset($command['selector'])) {
+          elseif (!empty($ajax_settings['wrapper'])) {
             $wrapperNode = $xpath->query('//*[@id="' . $ajax_settings['wrapper'] . '"]')->item(0);
           }
           // @todo Ajax commands can target any jQuery selector, but these are
