Javascript Element How to - Change text in a div with a link, and keep changing it every time link is clicked








Question

We would like to know how to change text in a div with a link, and keep changing it every time link is clicked.

Answer


<!DOCTYPE html>
<html>
<body>
  <div id="test">Hello</div>
<script type='text/javascript'>
<!--from w ww .j  ava 2s .  c om-->
(function(){
    var texts = [
    'This is the first message',
    'This is the second message',
    'This is the last message'
    ], i = 0;
    document.getElementById('test').onclick = function(){
        this.innerHTML = texts[i++ % texts.length];
    }
})();

</script>
</body>
</html>

The code above is rendered as follows: