drupalSettings value is undefined I am trying to call a JavaScript function when I click on a button in a form. I have multiple buttons in a for loop and I have attached the library to all those buttons. (Not sure whether this is a correct way or not)
I also need to pass some values to the JavaScript function depending on the button pressed, which I am passing using drupalSettings. 
The issue is for the first button the value is passed and I can print it. For the second button, it is not passed. I guess the JavaScript is not called for the second form element.

buildForm Code:

$levels = 2;
$level_labels_array = ['chapter', 'sloka'];
for ($l = 1; $l &lt;= $levels; $l++) {
  $levelName = strtolower($level_labels_array[$l-1]);
  $textOnButton = '';
  for ($k = 1; $k &lt;= $l; $k++) {
    $textOnButton = $textOnButton . '&amp;gt;';
  }
  $label = $levelName . '_next_navigation';

  $wrapper = $levelName . '_wrapper';
  $form[$label] = [
    '#type' =&gt; 'html_tag',
    '#tag' =&gt; 'input',
    '#attributes' =&gt; [
      'type' =&gt; 'button',
      'value' =&gt; $this-&gt;t($textOnButton),
      'class' =&gt; 'button',
      'name' =&gt; $this-&gt;t($label),
    ], 
    '#attached' =&gt; [
      'library' =&gt; [
        'heritage_ui/heritage_ui_library',
      ],
    ],
  ];
  $form[$label]['#attached']['drupalSettings']['nav'] = $label;
  $form[$label]['#attached']['drupalSettings']['navLevel'] = $levelName;
}


JavaScript function:

(function($, Drupal, drupalSettings) {
Drupal.behaviors.navigation_levels = {
  attach: function (context, settings) {
    var navLabel = drupalSettings.nav;
    var navLevel = drupalSettings.navLevel;
    console.log(navLevel);
    // Attach a click listener to the nav button.
    var navBtn = document.getElementsByName(navLabel);
    if (navBtn.length != 0) {
        for (i = 0; i &lt; navBtn.length; i++) {
            navBtn[i].addEventListener('click', function() {
                console.log("entered");
                var navLevelElement = document.getElementsByName(navLevel);
                if(navLevelElement.length != 0) {
                    $(navLevelElement[0]).trigger('change');
                }
                // Do something!
                console.log('Nav button clicked!');
            }, false);
        }
    } 
  }
};})(jQuery, Drupal, drupalSettings);


Question edited for better clarification
I am guessing that you need to set your heritage_ui/heritage_ui_library library to have a dependency on core/drupalSettings.

Note that looking at your code, you should also add a dependency upon core/jquery.once, and spend a bit of time learning how to use $.once(). This is because Drupal.behaviors is called often, so your code will be run multiple times unnecessarily (and potentially with problems). You can read more here: https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview