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?
Similar Posts
- Check if dark mode is enabled using Javascript
- Add class to an element in javascript
- Get Tag Name of an Element using Javascript
- Get all child elements of parent element in javascript
- Array.find() - get the very first element satisfy a condition Javascript
- Efficiently Remove the Last Element from an Array in JavaScript [6 Methods Explained]
- Javascript to find which DOM element has the focus