My button don’t toggle itself

Hello everybody I have a problem with my code, for some reason I cannot make my div box be with a lightblue backgroundcolor change to purple when I click on the button and change from purple to lightblue when I click again


<button onclick="myFunction()">Default Button</button>
<div id="myBox">


button {
	display: block;
	margin: 5px;
#myBox {
	margin: 5px;
	display: block;
	height: 150px;
	width: 250px;
        background-color: lightblue;
.light-blue {
  background-color: lightblue;

.purple {
  background-color: purple;

function myFunction() {  
  // Define myBox div
  const myDiv = document.querySelector("#myBox");
  // Do a check to see which color class myDiv    contains
	if (myDiv.classList.contains("light-blue")) {
	 // Remove light blue class
    // Add purple class
	else if(myDiv.classList.contains("purple")) { 
	  // Remove purple class 
    // Add light-blue class

Hi @charlms350, there’s no class is set initially on the box so neither condition in the click handler will be true. So you’ll either have to give the box an initial class, or make the else if a simple else so that will become the default action.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.