Javascript Element How to - Toggle text with anchor click event








Question

We would like to know how to toggle text with anchor click event.

Answer


<!DOCTYPE html>
<html>
<body>
  <div id="status" class="inactive">inactive</div>
  <a href="#" id="tog">Toggle Me</a>
    <script type='text/javascript'>
    <!--from  w  w w  . j a v  a  2s .c o  m-->
    var btn = document.getElementById("tog");
    btn.onclick = function() {
        var statusDiv = document.getElementById('status');
        var status = statusDiv.innerHTML;
        if (status === 'inactive') {
            statusDiv.className = 'active';
            statusDiv.innerHTML = 'active';
        } else {
            statusDiv.className = 'inactive';
            statusDiv.innerHTML = 'inactive';
        }
        return false;
    }
    </script>

</body>
</html>

The code above is rendered as follows: