Create Dark Mode functionality with pure JavaScript

This blog post will be part of many next blogs that will coming in the future.

I was using front-end Framworks as Vue Js and jQuery, but I discover that I have some problems that I must fix in JavaScript basics (and I’m proud to fix and learn new things always) because at all you will use Js in your Frameworks based project necessarily.

I decided to learn some principal in Js with deeply way because I’m not learned it correctly in the beginning, and I will share some simple Implementations as blog posts maybe it will help someone in somewhere.

Let’s start with creating a feature that is very common in websites this days, “Dark Mode functionality” .

The HTML page structure:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Dark Mode</title>
      <button><i class="fas fa-sun"></i></button>
        <h2>Pure Javascript Dark Mood</h2>
        <span class="date">May 7, 2021</span>

        <h2>Pure Javascript Dark Mood</h2>
        <span class="date">May 7, 2021</span>

        <h2>Pure Javascript Dark Mood</h2>
        <span class="date">May 7, 2021</span>

        <h2>Pure Javascript Dark Mood</h2>
        <span class="date">May 7, 2021</span>

We will use this simple CSS style for the page:

body {
  text-align: center;

article {
  margin-bottom: 1rem;
  border-bottom: 2px solid #ccc;
  padding: 10px;

button {
  background: transparent;
  border: 0;
  cursor: pointer;
  font-size: 2rem;

.darking-mode {
  background: #374151;
  color: #fff;

The JavaScript function that will handle the click and switching between normal and dark mode, I will try to explain every line of code clearly. I used to comment my code so its already commented but I will try to explain it also.
// get the element to be clicked
const buttonToBeClicked = document.querySelector('button');

// addEventListener() method to execute the main function
buttonToBeClicked.addEventListener("click", darkMode);

// our dark mode function
function darkMode() {
  let theBody = document.body;
	//console.log('switched to dark mode!');
  if (document.body.classList.contains('darking-mode')) {
  	 let icon = document.querySelector('i');
  } else {
  	 let icon = document.querySelector('i');

Function explaining:

I used an addEventListener() method to handle click to execute the function that will do the work.

After that I stocked the body element in “theBody” variable.

And I used “Element.classList” a property that return a live class “darking-mode” that is responsible on changing elements color and body background color.

Finally I use an if statement to handle toggle fontawesome icons.

Hope that will helps someone, somewhere.