A reminder to myself, because I’ve forgotten this too many times and had to look it up again and again.

if (window.matchMedia) {
  if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
    const body = document.getElementsByTagName('body')[0];
    body.classList.add('dark');
  }
}