Online Snippets Library

How to get index of element in jQuery

To get index of element, we use index() method of jQuery.The index() method returns position of given element from among the matched elements.If searched element is not found, index() method will return -1.

Syntax

$(selector).index()

Example

HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"> </script>
<title>How to get index of element in jQuery</title>
</head>
<body>
<span>Click a div!</span>
<div>First div</div>
<div>Second div</div>
<div>Third div</div>
</body>
</html>
Javascript
$(document).ready(function(){
$("div").click(function(){
var index = $( "div" ).index( this );
$( "span" ).text( "Div index is index #" + index );
 });
});