Javascript DOM How to - Receive index of nav element








Question

We would like to know how to receive index of nav element.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.10.1.js'></script>
<style type='text/css'>
li {<!--from  ww  w  .j a v a  2s.c om-->
  width: 100px;
  height: 100px;
  border: solid;
}
</style>
<script type='text/javascript'>
$(window).load(function(){
    $('body').on('click', '.button', function (e) {
        console.log($(this).index());
    });
});
</script>
</head>
<body>
  <ul>
    <li class="button">0</li>
    <li class="button">1</li>
    <li class="button">2</li>
  </ul>
</body>
</html>

The code above is rendered as follows: