Home > Enterprise >  How to use JavaScript to add a class after clicking and then remove it after clicking again?
How to use JavaScript to add a class after clicking and then remove it after clicking again?

Time:12-22

I just learned javascript not long ago, and I am practicing how to add color after clicking, and I can cancel the color when I click again!

But even though I checked on the Internet, I still don’t know which grammar is wrong?

Hope to get your guidance, thank you~

let add = document.querySelector('.add');
let box = document.querySelector('.box');


add.addEventListener('click',function(e){
  e.preventDefault();
  box.setAttribute('class','blue');
})
.add {
  display: block;
  margin-bottom: 100px;
}

.box {
  width: 100px;
  height: 100px;
  border: 1px solid;
}

.blue {
  background-color: blue;
}
<a  href="javascript:;">click</a>

<div ></div>

CodePudding user response:

classList.toggle is exactly what you need. It will remove the class if already present and add it if not. See this.

let add = document.querySelector('.add');
let box = document.querySelector('.box');

add.addEventListener('click',function(e){
  e.preventDefault();
  box.classList.toggle('blue');
})
.add {
  display: block;
  margin-bottom: 100px;
}

.box {
  width: 100px;
  height: 100px;
  border: 1px solid;
}

.blue {
  background-color: blue;
}
<a  href="javascript:;">click</a>

<div ></div>


Problem in your code:

box.setAttribute('class','blue');

this will always overwrite the class to 'blue'


As you're interested in doing this using setAttribute, the following is one way to do it.

let add = document.querySelector('.add');
let box = document.querySelector('.box');

// not recommended
add.addEventListener('click', function(e) {
  e.preventDefault();

  const existingClasses = box.getAttribute('class');
  const newClasses = (existingClasses.includes('blue') ? existingClasses.replace('blue', '') : `${existingClasses} blue`).trim();

  box.setAttribute('class', newClasses);
})
.add {
  display: block;
  margin-bottom: 100px;
}

.box {
  width: 100px;
  height: 100px;
  border: 1px solid;
}

.blue {
  background-color: blue;
}
<a  href="javascript:;">click</a>

<div ></div>

CodePudding user response:

You are missing an event handler in your javascript, that removes the class again. The only handler you have is the one adding blue.

box.addEventListener('click',function(e){
  e.preventDefault();
  box.removeAttribute('class');
})

CodePudding user response:

You should check if the box has a class and if so, remove & else add

You can do it like this;

box.classList.contains("blue") ? box.classList.remove("blue") : box.classList.add("blue")
  • Related