diff --git a/core/lib/Drupal/Core/Form/FormBuilder.php b/core/lib/Drupal/Core/Form/FormBuilder.php
index be000dc..5cad315 100644
--- a/core/lib/Drupal/Core/Form/FormBuilder.php
+++ b/core/lib/Drupal/Core/Form/FormBuilder.php
@@ -790,6 +790,9 @@ public function prepareForm($form_id, &$form, FormStateInterface &$form_state) {
         '#type' => 'hidden',
         '#value' => $form_id,
         '#id' => Html::getUniqueId("edit-$form_id"),
+        '#attributes' => [
+          'data-drupal-selector' => Html::getId("edit-$form_id"),
+        ],
         // Form processing and validation requires this value, so ensure the
         // submitted form value appears literally, regardless of custom #tree
         // and #parents being set elsewhere.
@@ -798,6 +801,8 @@ public function prepareForm($form_id, &$form, FormStateInterface &$form_state) {
     }
     if (!isset($form['#id'])) {
       $form['#id'] = Html::getUniqueId($form_id);
+    }
+    if (!isset($form['#attributes']['data-drupal-selector'])) {
       // Provide a selector usable by JavaScript. As the ID is unique, its not
       // possible to rely on it in JavaScript.
       $form['#attributes']['data-drupal-selector'] = Html::getId($form_id);
@@ -963,17 +968,14 @@ public function doBuildForm($form_id, &$element, FormStateInterface &$form_state
       $element['#array_parents'] = [];
     }
 
+    $unprocessed_id = 'edit-' . implode('-', $element['#parents']);
     if (!isset($element['#id'])) {
-      $unprocessed_id = 'edit-' . implode('-', $element['#parents']);
       $element['#id'] = Html::getUniqueId($unprocessed_id);
-      // Provide a selector usable by JavaScript. As the ID is unique, its not
-      // possible to rely on it in JavaScript.
-      $element['#attributes']['data-drupal-selector'] = Html::getId($unprocessed_id);
     }
-    else {
+    if (!isset($element['#attributes']['data-drupal-selector'])) {
       // Provide a selector usable by JavaScript. As the ID is unique, its not
       // possible to rely on it in JavaScript.
-      $element['#attributes']['data-drupal-selector'] = Html::getId($element['#id']);
+      $element['#attributes']['data-drupal-selector'] = Html::getId($unprocessed_id);
     }
 
     // Add the aria-describedby attribute to associate the form control with its
