-2

I Want to Remove all class except dpkCursor

<div class="dpkCursor active disk"></div>

I'm reseting it on mouseenter

   target.addEventListener("mouseleave", resetCursor);


   function resetCursor() {

     //  dpkCursor.classList.remove("active");

         dpkCursor.className = ""
         dpkCursor.classList.add(dpkCursor); // bad approach 
           
   }

I dont want to remove this class like this as because its breaking my css and cause flickers just remove all class except this What is the best way to do so

Dpk
  • 567
  • 5
  • 16
  • 3
    _"What is the best way to do so"_ - which ever way you write it that works and is easy to maintain. – evolutionxbox Aug 03 '21 at 13:22
  • 1
    I don't see anything wrong with your approach... – Terry Aug 03 '21 at 13:26
  • 1
    What is the issue with the way you did it? `dpkCursor.className = 'dpkCursor'` is one less step. Do you know what classes are added? – epascarello Aug 03 '21 at 13:26
  • See: https://stackoverflow.com/questions/5363289/remove-all-classes-except-one – yittoo Aug 03 '21 at 13:30
  • So just do `dpkCursor.className = 'dpkCursor'`...... no different than what you accepted other than `dpkCursor` is not hard coded. If you know what classes could be added `dpkCursor.classList.remove("foo", "bar", "baz");` – epascarello Aug 03 '21 at 13:42

2 Answers2

2

If you want to remove everything, the easiest thing is just set it back to the start

dpkCursor.className = 'dpkCursor';

If you know what classes could have been added, you can just remove them. If they are not there, it makes no difference. So just put all the classes that could be there in the remove method.

dpkCursor.classList.remove('foo', 'bar', 'baz');
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • @Dpk as long as you think it will always be first, then risk it. Hopefully something does not alter the order in the future. :) – epascarello Aug 03 '21 at 13:53
  • @epascarello because you're not doing it _exactly how the OP wants_, even if your answer is simpler. Maybe they need it to be dynamic, but then that should be specified in the question. – evolutionxbox Aug 03 '21 at 13:53
  • 1
    In the end, my guess is whatever you are doing could be done 100% in CSS and would not even need this. – epascarello Aug 03 '21 at 13:56
1

You could use also split function:

 target.addEventListener("mouseleave", resetCursor);


   function resetCursor() {
         dpkCursor.className = dpkCursor.className.split(' ')[0];
   }

This will set dpkCursor.className to first class (dpkCursor)

Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30