почему выдает ошибку Cannot read property 'setAttribute' of null?

Подскажите, что не так сделал?
В консоле на Live Server выдает ошибку Uncaught TypeError: Cannot read property 'setAttribute' of null

const btn = document.querySelector('.theme__button') /* находим кнопку <div class="theme__button">Switch theme</div> по селектору .theme__button и записываем ее в переменную btn */
const theme = document.querySelector('.theme') /* находим блок <div class="theme">, в котором будет меняться тема, по селектору .theme и записываем ее в переменную theme */

theme.setAttribute('data-theme', 'light') /* устанавливаем значение 'light' по-умолчанию */

btn.addEventListener('click', () => { /* при клике на кнопку <div class="theme__button">Switch theme</div> */
  if (theme.getAttribute('data-theme') === 'light') { /* если у блока <div class="theme"> атрибут 'data-theme' строго равен значению 'light'  */
    theme.setAttribute('data-theme', 'dark') /* тогда устанавливаем значение 'dark' */
  } else { /* а иначе */
    theme.setAttribute('data-theme', 'light') /* устанавливаем значение 'light' */
  }
})
:root {
  --theme-color: #efefef;
  --primary-color: #000e29;
}
.theme {
  background: var(--theme-color);
  color: var(--primary-color);
}
.theme__button {
  background: var(--primary-color);
  color: var(--theme-color);
}
[data-theme="light"] {
  --theme-color: #efefef;
  --primary-color: #000e29;
}
[data-theme="dark"] {
  --theme-color: #000e29;
  --primary-color: #efefef;
}
<div class="theme">
  <div class="theme__button">Switch theme</div>
</div>


Ответы (1 шт):

Автор решения: Igor

У Вас на странице нет элемента с классом theme в момент выполнения document.querySelector('.theme'). Заверните код в

window.addEventListener('load', function() {
  ...
});
→ Ссылка