jQuery Method How to - Get element index with index() method








Question

We would like to know how to get element index with index() method.

Answer


<!--  w ww  . j  a  v a2 s .c o m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script type='text/javascript'>
$(function(){
    $(':button').on('click', function(){
           console.log($(this).closest('.xyz').index('.xyz'));
    });
});
</script>
</head>
<body>
  <div id="abc">
    <h1>hello</h1>
    <div class="xyz">
      <input type="button">Click Me </input>
    </div>
    <h1>Hello 1</h1>
    <div class="xyz">
      <input type="button">Click Me</input>
    </div>
  </div>
</body>
</html>

The code above is rendered as follows: