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








Question

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

Answer


<!--from   ww w  .j av a2s  .com-->
<!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: