jQuery | index() with Examples
Last Updated : 01 Oct, 2024
The index() is an inbuilt method in jQuery that is used to return the index of the specified elements with respect to the selector.
Syntax:
$(selector).index(element)
Parameter:
It accepts an optional parameter "element" which is used to get the position of the element.
Return value:
It returns an integer denoting the index of the specified element.
Example: This example shows the working of index() function.
html <!DOCTYPE html> <html> <head> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> <!--jQuery code to demonstrate index function --> // document ready $(document).ready(function () { // if the list is clicked $("li").click(function () { // index() // to return the index of the clicked // element of the list document.getElementById("demo").innerHTML = "Clicked Index " + $(this).index(); }); }); </script> </head> <body> <p>Click on the elements of the list to display their index number with respect to the other elements in the list.</p> <ul> <li>Geeks</li> <li>for</li> <li>Geeks</li> </ul> <p id="demo"></p> </body> </html>
Output:
Example: This example shows the working of index() function.
html <!DOCTYPE html> <html> <head> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> <!--jQuery code to demonstrate index function --> // document ready $(document).ready(function () { // if the list is clicked $("li").click(function () { // index() // to return the index of the clicked // element of the list document.getElementById("demo").innerHTML = "Clicked Index " + $($(".myclass")).index($("#id")); }); }); </script> </head> <body> <p>Click on the elements of the list to display their index number with respect with the other elements in the list.</p> <ul> <li>Geeks</li> <li class="myclass">for</li> <li class="myclass" id="id">Geeks</li> </ul> <p id="demo"></p> </body> </html>
Output: