Skip to content
Advertisement

How can I toggle a class in CSS using JavaScript?

<i class="icon slash eye" id="test" 
  onclick="registerFunction(); myFunction(this);" 
  style="margin-bottom:-20px;cursor: pointer;float:right;"></i>

Script

<script>
function myFunction(x) {
    x.classList.remove("slash");
    }
</script>

It is changing slash eye to eye but not vice versa. How can I achieve that?

Advertisement

Answer

You are just removing the class with remove method.

Your question almost answered itself, as the solution to it is the toggle method.

<script>
    function myFunction(x) {
        x.classList.toggle("slash");
    }
</script>

With this simple change, your code should behave as you expect now.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement