-1

I currently have an increment and decrement methods on 2 buttons. My increment function is firing fine however my decrement method is failing. I want to subtract just from the variable so an example would be if I had the class "move2" and fired the decrement method I would get "move1" and so on...d

Any thoughts?

let i = 0;

const increment = (div) => {
    document.getElementById(div).classList.remove("move" + i++);
    document.getElementById(div).classList.add("move" + i); 
}

const decrement = (div) => {
    var hasClass = document.getElementById(div).classList.contains('move1', 'move2')
    if(hasClass === true)
        document.getElementById(div).classList.remove("move" + i--);
}
ruleboy21
  • 5,510
  • 4
  • 17
  • 34
user992731
  • 3,400
  • 9
  • 53
  • 83

1 Answers1

1

As @MikeMcCaughan mentioned, you need to use --i instead of i-- to use the decremented value on your class name. Also, your current boolean variable hasClass returns true only if the div has a class of class1 or class2. class3 and above returns false again.

Instead of using contains() you can use indexOf() instead to check the element class name and if it returns true, you can then use the .classList.replace() method to update the classname to the decremented value.

const decrement = (div) => {
   let className = document.getElementById('x').getAttribute("class"); // get element class value
   let hasClass = className.indexOf('move') >= 0; // returns true if class value has "move" in it
    if(hasClass === true)
      document.getElementById('x').classList.replace((className),("move" + --i));     // replace the class value with the decremented class name
}

jsFiddle with the above approach: https://jsfiddle.net/AndrewL64/rdjv5hsm/11/


Also if you want to cap the decrement at 0, you can edit the if condition from:

if(hasClass === true) {
    document.getElementById('x').classList.replace((className),("move" + --i));
}

To:

if(hasClass === true && i > 0) {
    document.getElementById('x').classList.replace((className),("move" + --i));
}

jsFiddle with decrement capping: https://jsfiddle.net/AndrewL64/rdjv5hsm/14/

AndrewL64
  • 15,794
  • 8
  • 47
  • 79