javascript

Add a CSS class to element if dark mode is enabled using Javascript

In this post, we are adding a class to an HTML element if the user has set dark mode on the system. We are using Javascript code for that.

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

In the above code example, we are checking the dark mode using window.matchMedia and assigning a class to the body tag, and this way, you can make the content inside it in dark theme.

You can set the body background of the document using CSS.

body {
   background: #000000;
   color: #fff;
}
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    document.getElementsByTagName("body")[0].setAttribute("data-theme", "dark");
}
Here, we are setting an attribute data-theme to dark if the system theme is set to dark mode.
Was this helpful?