'JavaScript can't select DOM element by ID in WordPress

Is there a way for JavaScript to interact with the DOM on a WordPress page. Or is interaction only possible through jQuery?

Button element in header.php:

<div id="settings" class="special-menu__item btn-settings">
            <button class="special-menu__title">
              <i style="margin-right: 10px" class="fa fa-cog" aria-hidden="true"></i>
        Настройки
    </button>
</div>

JavaScript Code:

const settingButton = document.getElementById("settings");
let toggle = false;
settingButton.addEventListener("click", function _f() {
  if (toggle === false) {
    settingButton.classList.add("active");
    settingOpen.classList.add("open");
  } else {
    settingButton.classList.remove("active");
    settingOpen.classList.remove("open");
  }
  toggle = !toggle;
  removeEventListener("click", _f);
});


Solution 1:[1]

I was having this issue too.

In the console, I could grab any element I wanted with getElementById or querySelector. But when I would select it in my custom JS code, it would be null.

To get around this, you can just add your code in a load event listener. This way, after the page loads, you can run your code and change the DOM element how you want. It might not be the most functional thing to watch, but it works.

example:

window.addEventListener('load', () => {
    const element = document.querySelector('#elementId');
    console.log('element I selected:', element)
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Just a Dude