Jquery .index() Function Example

Jquery .index() Function Example

By Yashwant Chavan, Views 1012, Date 26-Jun-2015

This Jquery tutorial will help you understand the concept of .index() method along with demo example. Some times we need to find out the index of selected element, clicked element or selected option then this index() function will help you.

tags jquery jquery-index

Jquery .index() Syntax

.index();
.index(element);
.index(selector);

.index(); This method signature does not accept any parameters. index() function return the integer value which indicate the position of the first element within the jquery object relative to its sibling elements.

$( "#red" ).index();

or 

$(this).index();

.index(element); In this element example, the DOM element is passed into .index() function which is being checked against all of the elements in the jquery objects set

var red = document.getElementById( "red" );
$( "li" ).index( red );

or

$( "li" ).index( $("span"));

.index(selector); In this element example, respected jquery selector value is passed to .index() function which will return the matching index value for selector element.


$( "li" ).index(".color");

Jquery .index() Example

In below example we just return the index of clicked div element. index() function gives the zero-based index of an element. Just play around the example and verify the output.

<head>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  
   <script>
      $(document).ready(function(){      
       $(".box").click(function(){  
        $("#output").html($(this).index());    
       });
      });  
   </script>   
</head>
<style>
   .box{  
   height:100px;
   width:100px;  
   padding:10px;
   margin:10px;
   float:left;
   display:inline-block;
   background:#ff9900;  
   }
</style>
<body>
   <h1>Jquery .index() function Example</h1>
   <div id="container">
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
   </div>
   <h2 id="output"> </h2>
</body>
</html>

Output

jquery .index() function example
Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]