Dark mode and light mode html, css, javascript how?

Hello and thank you in advance, I would like to make a button with darkmode and if you click on it then it becomes darkmode and the button is then called white mode then when you click on it again it becomes white mode and the button is called dark mode again.

Code:

<!DOCTYPE html> 
<html>
<head>
<style>
.page {
  padding: 25px;
  background-color: white;
  color: black;
  font-size: 25px;
}

.dark-mode {
  background-color: black;
  color: white;
}
</style>
</head>
<body>

<div class="page">Hello</div>

<button onclick="myFunction()">dark mode</button>

<script>
function myFunction() {
   var element = document.page;
   element.classList.toggle("dark-mode");
}
</script>

</body>
</html>

Answer

You are trying to toggle the dark-mode class on document.page, which doesn’t exist.

Instead, you should be toggling it on document.body.

<!DOCTYPE html> 
<html>
<head>
<style>
.page {
  padding: 25px;
  background-color: white;
  color: black;
  font-size: 25px;
}

.dark-mode {
  background-color: black;
  color: white;
}
</style>
</head>
<body>

<div class="page">Hello</div>

<button onclick="myFunction()">dark mode</button>

<script>
function myFunction() {
   var element = document.body;
   element.classList.toggle("dark-mode");
}
</script>

</body>
</html>

To only toggle the class on the div, use querySelector:

<!DOCTYPE html> 
<html>
<head>
<style>
.page {
  padding: 25px;
  background-color: white;
  color: black;
  font-size: 25px;
}

.dark-mode {
  background-color: black;
  color: white;
}
</style>
</head>
<body>

<div class="page">Hello</div>

<button onclick="myFunction()">dark mode</button>

<script>
function myFunction() {
   var element = document.querySelector('div.page');
   element.classList.toggle("dark-mode");
}
</script>

</body>
</html>