Vanilla Javascript Firing Twice I have some simple dom manipulation I want to make using javascript without jquery. I can't seem to figure out how to prevent this code from firing twice.

Almost all examples I find use jQuery, but I do not want to add jQuery just for this. I'm trying to use es6 with babel here.

((() =&gt; {
  Drupal.behaviors.node_page_filters_sales = {
    attach: (context, settings) =&gt; {

      const usaButton = document.querySelector('[data-sales-switcher="83"]');
      usaButton.style.border = '6px solid orange';
    }
  };
})());


This code works, but it is run twice. Once when there selector queried does not exist, giving me a typeError, and one when it does, executing the code as expected. 

It seems like it's related to BigPipe. If i turn that off, things seem to work as normal, firing once. But I obviously want BigPipe turned on. I'm clearly missing something that needs to be done when dealing with it.

For a little more detail, this is in a custom module. The custom module creates a block plugin. The javascript (snippet above) is part of the custom module's library that's attached to the block template.



UPDATED CODE EXAMPLE

The inline style was just for testing purposes. I'm attempting to check multiple buttons and add/remove classes based on a variable. See below.

// Determine default region.
let defaultLocation = '83';

if (defaultLocation === '83') {
    document.querySelector('.tid-83').classList.add('active');
}


I also notice that the javascript works as expected and is only executed once if I'm not logged in. When logged in, it fires twice.
I don't think you can force javascript to only run once. In addition to big pipe, any lazy loader, ajax form update (consider entity reference fields), or other ajax functionality on the page can trigger javascript to run again.

This is the issue that jQuery.once() addresses, and the reason it is used. It adds a class on the element, then executes on elements that do not have the class and adds the class. I expect you could reproduce this with something like the following.

const usaButton = document.querySelector('[data-sales-switcher="83"]');
if (!usaButton.classList.contains('node-page-filters-sales-once') {
  usaButton.style.border = '6px solid orange';
  usaButton.classList.add('node-page-filters-sales-once');
}