Paige Andrews
Paige Andrews

Reputation: 29

javascript remove last class assigned OR replace last class with new class

let addDarkColor = ["darkAqua","darkPurple","darkGreen", "darkYellow", "darkOrange", "darkRed", "darkPink"];

Here is an array of my classes I want to replace per time it's ran

questionContainer.classList.add(addDarkColor[nextClicked])

This is what I currently have, just adding on a new class everytime, however, it stacks, obviously. It's working, but at the same time, I didn't want my questionContainer to have stacked classes like : "darkAqua","darkPurple","darkGreen", "darkYellow" everytime it is clicked. Is there a way to either remove the last class assigned to it before adding the class (so I dont have to specify each time WHAT class is being removed, just the last one assigned) Or preferebly, replace the last assigned class with my new class. I could not find an answer anywhere that wasn't JQuery. I do not know or have qjuery installed, so please help with vanilla Javascript

Upvotes: 1

Views: 527

Answers (1)

epascarello
epascarello

Reputation: 207537

You can also reference the previous class and remove it

let addDarkColor = ["darkAqua","darkPurple","darkGreen", "darkYellow", "darkOrange", "darkRed", "darkPink"];

var questionContainer = document.querySelector(".test")
var nextClicked = 0
function next() {

  var prev = nextClicked - 1
  if (prev < 0) {
    prev = addDarkColor.length - 1
  }
  
  questionContainer.classList
    .add(addDarkColor[nextClicked])
  questionContainer.classList
    .remove(addDarkColor[prev])
  
  nextClicked++
  if (nextClicked >= addDarkColor.length) nextClicked = 0
}

questionContainer.addEventListener("click", next)
next()
.darkAqua { background-color: aqua }
.darkPurple  { background-color: purple }
.darkGreen  { background-color: green }
.darkYellow  { background-color: yellow }
.darkOrange  { background-color: orange }
.darkRed  { background-color: red }
.darkPink  { background-color: pink }
<div class="test">Hello</div>

If you do not know what class it is, you can remove all the classes.

questionContainer.classList
  .remove(addDarkColor.join(' '))
questionContainer.classList
  .add(addDarkColor[nextClicked])

Upvotes: 1

Related Questions